I am using insert operation in vector. After doing first insert operation iterator needs to be reinitialized. but in case of set it is not required. Reason please?
std::vector<int> myvector;
int main()
{
vector<int>::iterator it; it = myvector.begin();
myvector.insert(it,10); it = myvector.begin(); // if I comment it will not work in case of vector but in case of SET it is working...
myvector.insert(it,10);
cout<<"size"<<myvector.size()<<myvector[1];
std::cin.get();
return 0;
}
In the first code block memory is ( usuually ) allocated in each insert operation.
In the second code block memory is not allocated and the iterator is valid. But in general case it is better do not think that the iterator is valid. The correct way of using insert is the following
In the case of first code block itself,
for C++ STL Set the second time
it = v.begin(); which is not required.....
can u please clarify ???
Eg:
int main()
{
std::set<int> myset;
set<int>::iterator it; it=myset.begin();
myset.insert(it,2);
myset.insert(it,9);
return 0;
}
Here only once we initialised iterator. my doubt is why only once in set and twice in vector?
Because vectors shall have one memory block for all its elements as built-in arrays have. In fact, return value of data() is the address of this dynamically allocated array.
sets does not required to have one single memory block to store their elements.
All depends on the internal organization of a container.