I want to insert an int value in a vector object at position -1, i.e. :
vector<int> v;
int p = 12;
vector<int>::iterator it = -1;
v.insert(it,1,p);
is it possible in c++ ? or it must always be positive ?
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.
Insertion using the
insertmethod occurs always before the specified iterator, so to insert at the first position (i.e. * before* the current first element) use:(you can omit the
countparameter, if you only insert a single element).Insertion at the last position can be done using the
end()iterator likeor, in case of vectors, using
push_back()likeFor accessing vectors, you can only use non-negative indices, i.e.
v[-1]is invalid.Also you cannot assign an integer to an iterator, mainly because the iterator encapsulates both, the position and the container it is refering to. If you want to ‘construct’ an iterator for a specified position, use additions like:
(Note, that addition to iterators only works for so called random access iterators, thus it depends on the container type.)