C++ sorting and keeping track of indexes

后端 未结 15 2173
甜味超标
甜味超标 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:28

    vector >a;
    
    for (i = 0 ;i < n ; i++) {
        // filling the original array
        cin >> k;
        a.push_back (make_pair (k,i)); // k = value, i = original index
    }
    
    sort (a.begin(),a.end());
    
    for (i = 0 ; i < n ; i++){
        cout << a[i].first << " " << a[i].second << "\n";
    }
    

    Now a contains both both our values and their respective indices in the sorted.

    a[i].first = value at i'th.

    a[i].second = idx in initial array.

提交回复
热议问题