views:

119

answers:

3

In C++, why is the following element access in a vector invalid?

void foo(std::vector<int>* vecPtr) {
  int n = vecPtr->size(); // ok
  int a = vecPtr->[0];    // invalid
}

Instead, we have to write the more cumbersome

  (*vecPtr)[0] = 1;

I think, the operator[] call should just have the same syntax like a method call, and I hate the extra star and parentheses. (I know C++ has a lot more serious issues, but this one annoys me every time when I have to type it ...)

A: 

You seem to know already that that is supposed to be invalid syntax, so what's the question? The only answer as written is "because that's the way the language is written".

Semantically, it's because that [] operator is essentially saying "compute offset from the supplied address"; it's not a method, it's an operator. The syntax you give just doesn't really feel like it makes sense.

Also, because the syntax you describe looks terrible, as you're just pointing at a bare operator instead of the expected member.

Consider using references if you want to be more direct about your indirection (symbol crash).

phoebus
it IS a method on std::vector
sean e
No, it's a method if you write it as a method. As written, it's an operator (overloaded, but an operator nonetheless).
phoebus
+12  A: 

It's because the language expects a member to appear after ->. That's how the language is made up. You can use the function call syntax, if you like

// not really nicer
vecPtr->operator[](0);

If you have to do this a lot in sequence, using [0] instead of the parentheses can improve readability greatly

vecPtr[0][0]

Otherwise, for one level, i find (*vecPtr)[0] is perfectly readable to me.

Johannes Schaub - litb
+1 Also, you could assign the vector to a ref, and thats it!
AraK
But operator[] is a member.
Nice job on the "operator as a method call" ... You beat me to it :) +1
jheddings
@dehmann, yes `[]` are the tokens for that operator, but the name for it is `operator[]`. That's why you can do `->operator[](0)`. You cannot do `->[0]`, for the same reason you cannot do `->++;`, although i would agree being able to do `->[0]` would be some nice feature.
Johannes Schaub - litb
There is a usenet thread about this exact problem of overcoming `->operator[](i)`: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/921c27398e5114f3/987c08ce7f209bea
Johannes Schaub - litb
Thanks litb, now I see the problem.
+5  A: 

In addition to litb's nice answer I should say that there is a function at in vector class that allows you to use it as follows:

 int a = vecPtr->at(0);

The difference between this member function and member operator function operator[] is that vector::at signals if the requested position is out of range by throwing an out_of_range exception.

Kirill V. Lyadvinsky