c++ - 按字符串中的整数排序函数
问题描述
我有一个带有以下字符串的向量(例如): 0:“John - 204”1:“Jack - 143”2:“Alex - 504”,我想按数字对它们进行排序,这样它就会变成 Jack, John ,亚历克斯。我正在使用以下代码:
bool myfunc(string i, string j) {
return (stoi(i) < stoi(j));
}
sort(v1.begin(), v1.end(), myfunc); // sorts the players based on their position
for (unsigned int i = 0; i < v1.size(); i++) {
cout << v1[i] << endl;
}
但显然stoi函数在这种情况下不起作用......如果有人对我如何实现这一点有任何其他想法,我将不胜感激:)
谢谢!
解决方案
我会采用稍微不同的方法,使用std::stringstream
s:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
bool myfunc(std::string p1, std::string p2) {
bool result;
char ch;
int p1int, p2int;
stringstream comparator(p1 + " " + p2); //initialize stringstream
while(comparator >> ch && !(isdigit(ch))); //read until the first digit
comparator.putback(ch); //put it back
comparator >> p1int; //read the int
while (comparator >> ch && !(isdigit(ch))); //read until first digit
comparator.putback(ch); //put it back
comparator >> p2int; //read the whole int
result = p1int < p2int; //get the result
return result; //return it
}
int main() {
std::vector<std::string> v1 { "John - 204","Jack - 143","Alex - 504" };
sort(v1.begin(), v1.end(), myfunc); // sorts the players based on their position
for (unsigned int i = 0; i < v1.size(); i++) {
cout << v1[i] << endl;
}
}
输出:
Jack - 143
John - 204
Alex - 504
有关 std::stringstreams 的更多信息:https ://www.cplusplus.com/reference/sstream/stringstream/ 。
另外,请阅读为什么是“使用命名空间标准;” 被认为是不好的做法?.
当你将你的字符串传递给 std::stoi 时,它有一些不是数字的东西,所以它失败了,这就是你的代码不起作用的原因。
推荐阅读
- tensorflow - 在 tensorflow 2 中冻结子层
- html - 反序列化 API 响应并将其显示在视图循环中
- docker - Docker Compose:运行命令然后检索文件
- javascript - 需要在 javascript 中使用 firestore 的帮助
- sqlite - FutureBuilder 在不触摸屏幕的情况下无法工作
- c++ - 基于 for 循环的无辜范围不起作用
- android - android推送的FCM消息中的`ttl`和`time_to_live`属性有什么区别?
- python - 根据给定的汉明距离折叠字符串集
- django - 提交表单并从输入字段中检索值后重定向到另一个页面
- c++ - 用于 localhost:Port 的 MSVC++ 中的 TLS 客户端