在排序时跟踪向量对索引
keeping track of vector pair indices upon sorting
以前也有人问过类似的问题,但我在应用这个概念时遇到了麻烦。我想在我的成对向量中跟踪成对的下标,然后,一旦排序,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;
}
相关文章:
- 在C++中调整向量中的索引
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 将转换字符键入 int 以用作向量C++的索引
- 在对向量中查找元素的索引
- 如何检查类实例向量的索引是否为空
- 如何根据排序索引的向量对 std::index 集进行排序?
- C++ 中字符串向量的索引
- 如何在C++中返回向量的从零开始的索引
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 引用向量中的特定索引
- 在C++中从距离矩阵创建索引向量的最快方法
- 在python gdb脚本中索引c ++向量
- 使用索引向量擦除另一个向量的索引
- 根据索引向量对向量重新排序 - 更新
- C++11将智能指针的索引向量作为类的成员
- 使用auto关键字填充双索引向量
- C++对不带lambda的索引向量进行排序
- 如何从Eigen中的索引向量中提取子向量(Eigen::Vector)
- 通过索引向量对犰狳矩阵的所有列进行排序的最佳方法