【问题标题】:C++ Vector Sort String IssueC++ 向量排序字符串问题
【发布时间】: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
  • 数值上,应该更清楚了。

标签: c++ string sorting vector


【解决方案1】:

std::sort 正在按照您的要求做:它按字典顺序对字符串列表进行排序。要按数字排序,您需要将自定义比较器传递给sort,它将字符串作为数字进行比较。例如:

std::sort(std::begin(Nums), std::end(Nums)
          [] (const std::string& lhs, const std::string& rhs) {
              return std::stoi(lhs) < std::stoi(rhs);
          });

这使用标准库中的函数stoi 将字符串转换为ints 以​​进行比较。

【讨论】:

    【解决方案2】:

    我以更简单的方式提供了同样的东西。您必须使用自定义 comparison 才能实现此目的。

    bool cmp(string a,string b)
    {
         int p=convertToNum(a); //can use custom function or std::stoi
         int q=convertToNum(b); // converting string to integer
         return p<q;
    }
    sort(Nums.begin(), Nums.end(),cmp);
    

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      相关资源
      最近更新 更多