Using C ++ vector :: insert () to add to the end of a vector

I am writing a small piece of code where I will have to embed the values ​​in the STL STL vector in a certain place depending on the values ​​in the vector elements. I use the insert() function to accomplish this. I understand that when I want to add a new element to the end of the vector, I could just use push_back() . But for my code to look good, I would like to use exclusively insert() , which takes an iterator as input, pointing to the element after the desired insertion point and the value to be inserted. If the iterator value is passed as an argument to v.end() , where v is my vector, will it work the same as push_back() ?

Thank you so much!

+44
c ++ iterator vector stl
May 11 '11 at 7:55 a.m.
source share
2 answers

a.push_back(x) is defined as identical semantics for (void)a.insert(a.end(),x) for sequence containers that support it.

See table 68 in ISO / IEC 14882: 2003 23.1.1 / 12 [lib.sequence.reqmts].

+74
May 11 '11 at 8:03 a.m.
source share
β€” -

There is a slight difference that push_back returns void whether the insert iterator returns the element just inserted.

By the way, there is another way to check if they are doing the same thing: compile the following codes

 int main() { std::vector<int const> v; v.push_back(0); return 0; } 

the compiler will print a lot of annoying messages, just read it and you will find push_back calls insert (if not, try compiling v.insert(v.end(), 0) to see if they called the same insert function) at the end .

+14
May 11 '11 at 9:05
source share



All Articles