C++ 对成对向量排序
我在尝试对类型的向量进行排序时遇到了intro问题: 载体 我希望它们按照第一对中的第一个字符串排序 sortall_pairs.begin,all_pairs.end,comp 其中所有的_对是我的向量,comp是C++ 对成对向量排序,c++,sorting,vector,stl,C++,Sorting,Vector,Stl,我在尝试对类型的向量进行排序时遇到了intro问题: 载体 我希望它们按照第一对中的第一个字符串排序 sortall_pairs.begin,all_pairs.end,comp 其中所有的_对是我的向量,comp是 bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b) { string te
bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b)
{
string term1 = a.first;
string term2 = b.first;
return term1<term2;
}
如果我的初始向量是:
Z、 a,1
Y、 a,2
十、 a,3
我希望我的输出是:
十、 a,3
Y、 a,2
Z、 a,1
你能帮我吗?
谢谢
[编辑]:正如我所说,代码是更大程序的一部分,所以我的代码一定有问题。我将在取得进展的同时更新此内容。谢谢。您的代码确实如此,所以我不确定问题出在哪里
vector<pair<string, pair<string, int>>> v =
{
std::make_pair("Z", std::make_pair("a", 1)),
std::make_pair("Y", std::make_pair("a", 2)),
std::make_pair("X", std::make_pair("a", 3)),
};
std::sort(v.begin(), v.end(), comp);
for (const auto& p : v)
{
std::cout << "(" << p.first << ","
<< "(" << p.second.first << ","
<< p.second.second << "))\n";
}
通过删除不必要的局部变量,可以稍微改进比较器功能:
return a.first < b.first;
使用std::pair或中的运算符
演示
我不在乎你的代码是否有效:p我做了一些努力顺便说一句,为了扩展上面的副本,这里有两个版本,有一些小的改进。 更便宜:
bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b)
{
const string& term1 = a.first; // saves copying these strngs for no reason
const string& term2 = b.first;
return term1<term2;
}
更短更便宜:
bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b)
{
return a.first<b.first;
}
问题是什么?你所做的没有用吗?请注意,没有必要制作所有这些副本。我对其进行了测试。代码确实有效。不,它不起作用。代码实际上是一个更大程序的一部分,但它不是work@user2536272你的答案是肯定的。这个答案没有多大意义。它已经在代码工作的注释中建立起来了。std::pair不应该已经这样做了吗operator@chris的确是的,我是另一个傻瓜:他们只想根据第一个字符串排序。
bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b)
{
const string& term1 = a.first; // saves copying these strngs for no reason
const string& term2 = b.first;
return term1<term2;
}
bool comp(const pair<string, pair<string, int>> &a, const pair<string, pair<string, int>> &b)
{
return a.first<b.first;
}