2

Firstly I am new to C++ so may be the question is stupid !! Secondly I have already seen the related answers to this and can conclude that name of a vector could be treated as an array.

vector <int> myVector(7,10);   // creates a vector of size 7 and initializes with 10

We may use the name myVector as an array and write like myVector[0], myVector[1]...

But since vector is a class and myVector is it's object there should be storage area inside that object which could be treated as an array like myVector.someArray[0], myVector.someArray[1] not the object name itself how does that become possible?

Mat
  • 202,337
  • 40
  • 393
  • 406
Kush
  • 41
  • 6

1 Answers1

0

very simple, overloaded operators:

operator overloading

When you define in your class these kinds of methods, you get to use those special operators; the ones which already can be used with primitive data types as the standard describes.

In case of vector you have something like

...

const Element& operator[](const unsigned int index)
{
     return internalArray[index];
}

...

within its class declaration.

Something similar you will find in the std::vector class, so you can even build your own vector class if you'd like to do that.

For clarification, if a class has the []-Operator defined, you can do something like this with its object:

vec[4];

which is equivalent to:

vec.operator[](4);

That also means the parameter of the overloaded operator can be chosen. You could even pass a string to the [] operator.

For example std::map does that very nicely:

std::map -> Check out the example

Gerhard Stein
  • 1,543
  • 13
  • 25
  • You [should probably](https://stackoverflow.com/a/4421719/4850111) provide a `const Element& operator[]` too. – nada Apr 24 '20 at 07:06
  • @nada: Though not required, in this case better to do also for the parameter, you are right. Thank you! – Gerhard Stein Apr 24 '20 at 07:12