在排序时跟踪向量对索引

keeping track of vector pair indices upon sorting

本文关键字:索引 向量 跟踪 排序      更新时间:2023-10-16

以前也有人问过类似的问题,但我在应用这个概念时遇到了麻烦。我想在我的成对向量中跟踪成对的下标,然后,一旦排序,std::计算输入顺序。

cin >> 5 6 1 5 1 2 1 2 3 5
cout << 1 2 1 2 1 5 3 5 5 6
cout >> 3 4 2 5 1  //and this is where I am having trouble.

我正在考虑转换为三元组,其中一个元素是索引,但我无法使其符合我的需求。

任何帮助都会很感激。谢谢你。

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
using namespace std;
bool compare(const pair<int,int>&A, const pair<int,int>&B);
int main()
{
    vector<pair<int,int>> v;
    pair<int,int> tok;
    while(cin >> tok.first>>tok.second){v.push_back(tok);}
    sort(v.begin(),v.end(), compare);
    for(int i = (signed int)v.size()-1; i >= 0 ; i--)
    {
        cout << v.at(i).first << " ";
        cout << v.at(i).second << " ";
    }
    cout << endl;
    return 0;
}
bool compare(const pair<int,int>&A, const pair<int,int>&B)
{
    return A.first > B.first;
}

有一种方法可以做到。好久没有帮别人做作业了;-)

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

const string input_data = "5 6 1 5 1 2 1 2 3 5";
typedef pair<int, int> integer_pair;
typedef pair<int, integer_pair> integer_pair_with_input_order;
bool less_by_integer_pair(const integer_pair_with_input_order& l,
                             const integer_pair_with_input_order& r)
{
    return l.second < r.second;
}
int main()
{
    // note - I did this to avoid having to type numbers in.
    std::istringstream simulate_cin(input_data);
    vector<integer_pair_with_input_order> v;
    integer_pair tok;
    int input_order = 0;
    while(simulate_cin >> tok.first >> tok.second) {
        v.push_back(make_pair(++input_order, tok));
    }
    sort(v.begin(),v.end(), less_by_integer_pair);
    for (int i = 0 ; i < v.size() ; ++i)
    {
        const integer_pair_with_input_order& elem = v[i];
        cout << "input order : " << elem.first
        << " { " << elem.second.first
        << ", " << elem.second.second << " }n";
    }
    return 0;
}