Hi,

I want to prevent the sorting and preserve the original order in my container. below is the example.
How can I do it ?

   string one = "6";
   string two = "7";
   string three = "2";
   string four = "8";

   veck.push_back(one);
   veck.push_back(two);
   veck.push_back(three);
   veck.push_back(four); 

   veck.push_back("9");
   veck.push_back("12");
   veck.push_back("13");
   veck.push_back("5");



   I want to preserve the order of elements in my Vector which should be:-

   6, 7, 2, 8, 9 ,12 ,13, 5

   but when I try to insert into some other container using for loop it becomes sorted :

   2, 5, 6, 7, 8, 9, 12, 13

   e.g, 

   for(int i =0; i < veck.size(); i++){
       newVec.push_back(veck[i]);
   }

   Howto preserve the order of elements in my original container and avoid sorting ?

Thanks

Check your code again. The looping construct you have used does simple insertion which you want and doesn't sort the vector in any way.try your code on an integer vector may be to confirm the problem.

A technique I have used is to use another int array that represents the index values of the original array or vector. Sort the vector as normal but instead of swapping vector values you would swap the index array values. You could use std::sort() for this if sort the index array and write the comparison function to compare strings in the vector

vector<string> myvector;
bool compare(int& a1, int& a2)
{
   return myvector[a1] < myvector[a2];
}

int main()
{
   vector<int> index;
   index.resize(10);
   for(int i = 0; i < 10; i++)
       index[i] = i;
   std::sort(index.begin(),index.end(),compare);
   // display the sorted vector
   for(int i = 0; i < 10; i++)
     cout << myvector[index[i]] << '\n';
}

Actually I am using it like this and the inner if loop is creating problems for me

int count = 0;
          while(pch != NULL)
          {
             if(++count){
                          for ( int i = 0 ; i < vec.size(); i++ ){
                                 if(count==vec[i]){
                                            cout << vec[i] << endl;
                                            vec.push_back(pch);
                                 }
                          } 
              }
                 pch = strtok(NULL,"\t");
          }

It works fine when I comment //if(count==vec)

You can't compare char* with an it -- just won't work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.