C++ sorting and keeping track of indexes

后端 未结 15 2013
甜味超标
甜味超标 2020-11-22 10:01

Using C++, and hopefully the standard library, I want to sort a sequence of samples in ascending order, but I also want to remember the original indexes of the new samples.<

15条回答
  •  名媛妹妹
    2020-11-22 10:07

    There are many ways. A rather simple solution is to use a 2D vector.

    #include 
    #include 
    #include 
    using namespace std;
    
    int main() {
     vector> val_and_id;
     val_and_id.resize(5);
     for (int i = 0; i < 5; i++) {
       val_and_id[i].resize(2); // one to store value, the other for index.
     }
     // Store value in dimension 1, and index in the other:
     // say values are 5,4,7,1,3.
     val_and_id[0][0] = 5.0;
     val_and_id[1][0] = 4.0;
     val_and_id[2][0] = 7.0;
     val_and_id[3][0] = 1.0;
     val_and_id[4][0] = 3.0;
    
     val_and_id[0][1] = 0.0;
     val_and_id[1][1] = 1.0;
     val_and_id[2][1] = 2.0;
     val_and_id[3][1] = 3.0;
     val_and_id[4][1] = 4.0;
    
     sort(val_and_id.begin(), val_and_id.end());
     // display them:
     cout << "Index \t" << "Value \n";
     for (int i = 0; i < 5; i++) {
      cout << val_and_id[i][1] << "\t" << val_and_id[i][0] << "\n";
     }
     return 0;
    }
    

    Here is the output:

       Index   Value
       3       1
       4       3
       1       4
       0       5
       2       7
    

提交回复
热议问题