jeudi 26 octobre 2017

How to insert elements while maintaining sorted order for a STL::vector without using sort() function [duplicate]

This question already has an answer here:

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