-3

I am trying to buld the vector library . The code looks like this

#include <iostream>
#include <string>

namespace std
{
   template<typename T>
   class vector
   {
      private:
      T* value;
      T* temp;
      int arraySize{1};

      public:
      vector()
      {
        value=NULL;
        temp=NULL;
      }

      int size()
      {
          return arraySize;
      }

      void push(T val)
      {
        if(value==NULL)
        {
          value=new T[arraySize];
          value[arraySize-1]=val;
        }
        else if(value!=NULL)
        {
          arraySize=arraySize+1;
          temp=new T[arraySize];
          int lastIndex=arraySize-1;
          for(int j=0;j<lastIndex;j++)
            {
              temp[j]=value[j];
            }
          temp[lastIndex]=val;
          delete[] value;
          value=temp;
          temp=NULL;
        }
      }

      T pop()
      {
        int popIndex=arraySize-1;
        T t = value[popIndex];
        arraySize=arraySize-1;
        if(arraySize>=0)
        {
          temp=new T[arraySize];
          for(int j=0;j<popIndex;j++)
            {
              temp[j]=value[j];
            }
          delete[] value;
          value=temp;
          temp=NULL;
          return t;
        }
        else if(arraySize<0)
        {
          std::cout<<"Memory underflow\n";  
          reset();
        }
      }

      T operator[](int index)const
      {
        return value[index];  
      }

      T front()const
      {
          return (value[arraySize-1]);
      }

      T back()const
      {
          return (value[0]);
      }

      private:
      void reset()
      {
        arraySize=1;
        vector();
      }
   };
}

int main() 
{
  std::vector<std::string> v;

  v.push("1");
  v.push("2");
  v.push("3");

  std::cout<<"the element is : "<<v[1]<<"\n";

  std::cout<<"front element is : "<<v.front()<<"\nback(last) element is : "<<v.back()<<"\n";

  std::cout<<"size : "<<v.size()<<"\n";
  std::cout<<v.pop()<<"\n";
  std::cout<<v.pop()<<"\n";
  std::cout<<"size : "<<v.size()<<"\n";

  v.push("4");

  std::cout<<"size : "<<v.size()<<"\n";
  std::cout<<v.pop()<<"\n";
  std::cout<<"size : "<<v.size()<<"\n";
}

I have overloaded this [] operator for v[1] but i want to write as this for example
v[2]="2";

How should I do it Please help . And please suggest some changes in code if they are to be done

I tried to look for overloading of = operator but it tells that you can take only one argument

  • 4
    How about `T& operator[](int index) { return value[index]; }`? – Eljay Jun 15 '23 at 11:37
  • 9
    you should not add things to namespace `std`. Even if you do not include `vector` directly others headers might do, or might have a forward declaration. Just make it `my::vector` and all is fine – 463035818_is_not_an_ai Jun 15 '23 at 11:41
  • And just curious why do you initialize array size by 1? That might get you into of-by-one bugs later. It is also more customary to maintain sizes using std::size (an unsigned type) so you cannot accidentally work with negatively sized data. – Pepijn Kramer Jun 15 '23 at 11:41
  • you should look at how `std::vector::operator[]` is actually specified: https://en.cppreference.com/w/cpp/container/vector/operator_at. It does not return `T` – 463035818_is_not_an_ai Jun 15 '23 at 11:42
  • `front` and `back` also should not return `T`. Frankly I wonder what you use to guide your implementation. I hope it is not guessing. I consider myself somewhat familiar with `std::vector` but if I had to guess only I would get it wrong totally – 463035818_is_not_an_ai Jun 15 '23 at 11:45
  • https://en.cppreference.com/w/cpp/container/vector/front and https://en.cppreference.com/w/cpp/container/vector/back – 463035818_is_not_an_ai Jun 15 '23 at 11:46
  • and you must read this: https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three. Imho the rule of 3/5 is something to be considered right from the start, its not something to be added later. Currently your `vector` is totally broken, its extremely easy to use it in a way that will result in crashes or worse – 463035818_is_not_an_ai Jun 15 '23 at 11:48
  • 4
    You don't need to keep the `temp` around all the time. It is much cheaper to just create it inside the functions that need it. And also, the `vector()` inside `reset` doesn't clear *this* vector, but a new temporary vector that then immediately goes away again. – BoP Jun 15 '23 at 11:49
  • this is not how you reset an instance `vector();`. Really no offense, but you should start with a good introductory book https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. Your code looks like you are either guessing how the language works or the learning material you are using is seriously flawed. – 463035818_is_not_an_ai Jun 15 '23 at 11:50
  • 1
    `v[2] = "2";` has nothing to do with overloading `vector::operator=`. `vector::operator=` is for assigning vectors, when you write `v[2]="2";` you are assigning a string not a vector. The problem is that your `vector::operator[]` is returning the wrong type. It should return `T&` not `T`. Then you will be able to write`v[2]="2";`. – john Jun 15 '23 at 11:54
  • @463035818_is_not_a_number Thank You for recommendation , for this implementation yes I was just trying to write a vector library that would just work like it i.e i was just guessing . I do learn from learncpp.com , that is good source . And nothing of your words are harsh :-) I am a sort of begginer if i may say so – satej dhakane Jun 15 '23 at 12:38
  • @john Can you please tell why will it work by doing T& and not T . and I thought that the confussion might occur but I was not talking about vector::operator= – satej dhakane Jun 15 '23 at 12:41
  • @satejdhakane If you return `T` then you are returning a **copy** of the string in the vector. Even if it was legal to assign to that it would not change the vector because it's a copy, not the original string in the vector. If you return `T&` then you are returning a **reference** to the string in the vector. When you assign to a reference you assign to the target of the reference, which in this case is the string in the vector. – john Jun 15 '23 at 12:52
  • @john Ok Thanks – satej dhakane Jun 15 '23 at 13:03

1 Answers1

0

Lets break this down to a simpler example, because frankly, your code has too many issues to be addressed in a single answer. The comments mention some of them, you should take them serious, because your vector is very broken. Lets consider only implementation of a method that returns something that you can assign to. In other words, we want to write this code:

int main() {
     foo f;
     f.set("123");       // sets a member
     f.get() = "42";     // gets something that can be used to 
                         // assign to the member
     std::cout << f.get() << "\n";
}

And output should be 42.

We need a default constructor. We need a push method to set a string. A single string as member is sufficient. To get f.get() = "42"; working you do not need to implement an operator=. What is assigned is a string. std::string already has an operator=. However, get() should return a reference to the internal string. It should not return a copy of the internal string, because modifying that copy will have no effect on the member. Return a reference.

struct foo {
    std::string data;

    void set(const std::string& x) { data = x; }

    using reference = std::string&;

    reference get() { return data; }
    
};

Live Demo

For futher reading I recommend...

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185