【发布时间】:2016-03-04 20:11:33
【问题描述】:
好的,我有一个小任务,我需要使用 std::sort 对字符串向量进行排序,但它不会正确排序两个摘要以上的任何“数字”。使用此 API 进行作业至关重要。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> Nums = { "1", "5", "34", "3", "6", "12", "21" };
sort(Nums.begin(), Nums.end());
for (int i = 0; i < Nums.size(); i++)
{
cout << Nums[i] << endl;
}
system("PAUSE");
}
结果:
1
12
21
3
34
5
6
Press any key to continue . . .
想要:
1
3
5
6
12
21
34
【问题讨论】:
-
您想对字符串进行数字排序还是字典排序?即列表应该开始(“1”,“3”,...)还是(“1”,“12”,...)?
-
这是使用字符串排序。如果要按数值对它们进行排序,请在调用
sort时使用自定义比较器。更多信息在这里:en.cppreference.com/w/cpp/algorithm/sort -
数值上,应该更清楚了。