Hello,
Im starting my journey with vectors. Lets say I got a vector of ints with data like 10, 20, 30. I would like to put a 15 between 10 and 20 how to do this? I guess I should use Vector::insert but I dont really get this iterator thing :( Is there anyone kind enough to write some kind of example of declaring vector putting some data in it and inserting something between some specific elements?
Thanks for your replies. Can we write for example 1 instead of begin()+1?
I dont get this auto c:v I saw it somewhere. It is some kind of thing that come up with new version of C++? How does it work? (A link maybe ;))
begin() and end() are the index numer of the first and the last thing in a vector?
Begin() and end() returns iterators. Think of them as pointers to values. begin() returns iterator to the first element, and end returns iterator to one-past-the last element (therefore you should not dereference it)
I dont get this auto c:v I saw it somewhere. It is some kind of thing that come up with new version of C++?
Yes, it is range-based for loop introduced in C++11
Ugh. It should be it everywhere: the number we are inserting.
We can write this line as:
1 2
auto iter = std::lower_bound(v.begin(), v.end(), it);
v.insert(iter, it);
.insert() member function takes two arguments: first is iterator where to insert and second what to insert.
lower_bound is function defined in <algorithm> header. It operates on sorted ranges (ascending by default) and returns iterator to first element not less than one provided. We can see it as returning iterator to where we can insert given element to preserve sorted property.
It takes iterators to beginning and end of the range and value to search for.
So when we use it with v.begin() and v.end() it can be seen as "search whole vector and find a place where we can safely insert given value it"