This question already has an answer here:
- Iterator invalidation rules 4 answers
I am beginner in c++. Can someone let me know how to insert elements while maintaining sorted order for a STL::vector(without inbuilt sort() functions )
I am getting segmentation fault.
Please find my code in below:
Code::
int main()
{
vector<int> k;
k.insert(k.begin(), 2);
k.insert(k.begin(), 1);
k.insert(k.begin(), 38);
k.insert(k.begin(), 4);
k.insert(k.begin(), 50);
int s= rand() % 40;
for (auto p = k.begin(); p != k.end(); p++)
{
if(s>*p)
{
auto m=k.begin()++;
k.insert(m, s);
}
else
{
k.insert(k.begin(), s);
}
}
for (auto p = k.begin(); p != k.end(); p++)
{
cout<<*p<<" ";
}
}
Aucun commentaire:
Enregistrer un commentaire