Sort by proxy (or: sort one container by the contents of another) in C++

前端 未结 7 895
失恋的感觉
失恋的感觉 2020-12-19 02:34

I have a set of data which is split into two arrays (let\'s call them data and keys). That is, for any given item with an index i, I c

7条回答
  •  不知归路
    2020-12-19 03:23

    You could use a map:

    int main() {
      vector keys;
      vector data;
      keys.push_back(5); data.push_back("joe");
      keys.push_back(2); data.push_back("yaochun");
      keys.push_back(1); data.push_back("holio");
    
      // load the keys and data to the map (they will automatically be inserted in sorted order by key)
      map sortedVals;
      for(int i = 0; i < (int)keys.size(); ++i) {
        sortedVals[keys[i]] = data[i];
      }
    
      // copy the map values back to vectors  
      int ndx=0;
      for(map::iterator it = sortedVals.begin(); it != sortedVals.end(); ++it) {
        keys[ndx] = it->first;
        data[ndx] = it->second;
        ++ndx;
      }
    
      // verify
      for(int i = 0; i < (int)keys.size(); ++i) {
        cout<

    Here's the output:

    ---------- Capture Output ----------
    > "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
    1 holio
    2 yaochun
    5 joe
    
    > Terminated with exit code 0.
    

提交回复
热议问题