按字符串中的整数对函数进行排序

时间:2021-05-27 14:26:51

标签: c++

我有一个包含以下字符串的向量(例如): 0:“约翰 - 204” 1:“杰克 - 143” 2:“亚历克斯 - 504” 我想按数字对它们进行排序,这样它就会变成杰克、约翰、亚历克斯。 我正在使用以下代码:

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 功能在这种情况下不起作用......如果有人对我如何实现这一点有任何其他想法,我将不胜感激:)

谢谢!

2 个答案:

答案 0 :(得分:0)

我会采用稍微不同的方法,使用 std::stringstreams:


#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/

另外,阅读Why is "using namespace std;" considered bad practice?

当你将你的字符串传递给 std::stoi 时,它有一些不是数字的东西,所以它失败了,这就是你的代码不起作用的原因。

答案 1 :(得分:-1)

当然 std::stoi 在这种情况下不起作用,因为您将整个字符串“John - 204”传递给 myfunc,并且该字符串具有字符值(“John”)有一个有效的转换(至少在这种情况下)到整数值

尽管您非常接近 - 在您的比较器函数(即 myfunc())中,考虑如何始终梳理 子字符串 204、143、504。老实说,我会写一个小的帮助函数来执行此操作(以解决诸如“John -204”(没有第二个空格字符)或“John -”(没有数字)之类的尴尬情况。

当然,如果您确信您将收到的字符串格式与您的示例一致,那么@lubgr 建议将 find_last_of 和 substring 一起使用是合理的

相关问题