我想为练习排序一个字符串向量.这些字符串只有0到9之间的数字,如[10 2 1 9 91],我想排序为[9 91 2 1 10]以达到最大数字(9912110).我使用该sort函数执行了以下代码
#include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
bool compare(string i1, string i2)
{
int a, b;
int i = 0;
int min_len = (i1.length() > i2.length()) ? i2.length(): i1.length();
while(i < min_len) {
a = (int) (i1.at(i) - '0');
b = (int) (i2.at(i) - '0');
if (a != b)
break;
i++;
}
if (a > b)
return true;
if (a < b)
return false;
if (i1.length() > i2.length())
return false;
return true;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
sort(a.begin(), a.end(), compare);
}
Run Code Online (Sandbox Code Playgroud)
问题是当我用参数执行时:
100
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
Run Code Online (Sandbox Code Playgroud)
给我以下错误:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted
Run Code Online (Sandbox Code Playgroud)
但是,如果我用99执行并删除最后一个数字,它可以正常工作.如果我尝试超过100(如101或102 ......)也会出现相同的错误.我想错误在compare函数中.
编辑:
bool compare(const std::string& i1, const std::string& i2)
{
int i = 0;
int min_len = (i1.length() > i2.length()) ? i2.length(): i1.length();
while (i < min_len) {
int a = (int) (i1.at(i) - '0');
int b = (int) (i2.at(i) - '0');
if (a > b)
return true;
if (a < b)
return false;
i++;
}
return (i1.length() < i2.length());
}
Run Code Online (Sandbox Code Playgroud)
比较函数std::sort应始终在给定相等参数的情况下返回false.但是你的函数返回true.请尝试以下修改
bool compare(string i1, string i2)
{
...
if (a > b)
return true;
if (a < b)
return false;
return i1.length() < i2.length();
}
Run Code Online (Sandbox Code Playgroud)
我猜测正在发生的事情是,std::sort当要排序的序列的大小> = 100时,在您的平台上会选择不同的算法.对于这种不同的算法,满足比较函数的要求是至关重要的.
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |