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 …)
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 likeIf you have to do this a lot in sequence, using
[0]instead of the parentheses can improve readability greatlyOtherwise, for one level, i find
(*vecPtr)[0]is perfectly readable to me.