desktop <ff*@sss.comwrote in news:f4**********@news.net.uni-c.dk:
Naresh Rautela wrote:
>On Jun 4, 8:29 am, desktop <f...@sss.comwrote:
>>Why does insert only work when specifying an iterator plus the
object to be inserted:
std::vector<intt;
std::vector<int>::iterator it;
it = t.begin();
t.insert(it,33);
If I use push_back instead I don't need to supply the iterator. But
what are the reason the insert only works with an iterator?
push_back by default inserts at the end of the container while insert
allows you to mention a position where you can insert.
Ok thanks for the info. When I want to extract an element from the
vector I would use something like:
t.at(0);
If you want bounds-checking... if not, then you can also use:
t[0]
Of course, assuming that there is a 0-th object in the vector.
But if I have a vector containing my own object that I have defined in
a class 'test' (with a getInt() function returning a private integer)
I would like to use iterators for this:
std::vector<test*t2;
std::vector<test*>::iterator it2;
it2 = t2.begin();
it2 == t2.begin(). And since the vector is empty, it2 == t2.end() as
well.
test* tt2 = new test(707);
t2.insert(it2,tt2);
With this insertion, you may or may not have invalidated any and all
iterators into the container.
*it2->getInt()
This may or may not be dereferencing an invalid iterator. If it is, then
it is Undefined Behaviour. Anything can happen. And, IIRC, the
precedence rules say you'd have to write that as:
(*it2)->getInt()
-(member selection) has a higher precedence than * (dereferencing).
But this does not work. Are iterators only used for inserting and not
extracting custom objects?
They're used for both. But you need to understand when iterators become
invalid. For vectors, any and all iterators into the vector may become
invalid upon insertion if the insertion causes a reallocation of the
vector.