首页 > 解决方案 > 按字符串中的整数排序函数

问题描述

我有一个带有以下字符串的向量(例如): 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函数在这种情况下不起作用......如果有人对我如何实现这一点有任何其他想法,我将不胜感激:)

谢谢!

标签: c++

解决方案


我会采用稍微不同的方法,使用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/ 。

另外,请阅读为什么是“使用命名空间标准;” 被认为是不好的做法?.

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


推荐阅读