If I have the following:
vector<int> v(4,0);
vector<int>* p = &v;
int element = p[0];
Will element be the same value as v[0]? I’m getting confused here about the [] operator.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Short answer: no.
What you have is not even valid C++.
p[0]is the same as*p, which is of typevector<int>and thus not convertible toint.The
[]-notation merely suggests that you think ofpas an array of vectors, and you are accessing the array’s first element, which isv. More generally, for any pointerp, the notationp[k]is identical to*(p + k)(in fact to a fault, as you can saya[5]and5[a]interchangeably).So if you really wanted to, you could write
p[0][i]for theith element of the vector, though it is more customary to just write(*p)[i](parentheses needed for the correct precedence).When I first skimmed over the question, I thought you might be looking for some clever hack and wanted to know whether
**(int**)(p)was equal tov[0]. That is indeed plausible, as the first element of the vector’s data structure is often the pointer to the vector’s internal buffer. Don’t use this at home.