对带有数字的字符串进行排序

pol*_*pts 3 c++ string

我有类似的字符串7X1234 XY1236 NM1235.我想使用最后4位数字对这些字符串进行排序,只忽略最初的两个字母.此外,我想比较这些数字,看看它们是否是连续的.

实现这一目标的一种方法我可以想到的是将这些字符串在字母和数字之间拆分为(7X and 1234)和工作词汇将数字字符串转换为int并对其进行处理.但是,我怎样才能将字母表部分再次与数字部分相关联,这是数字字符串排序和比较时如何7X再次前缀到?1234C++

总之,如果我有,7X1234 XY1236 NM1235 BV1238我需要得到7X1234 NM1235 XY1236 BV1238

我没有详细说明我想知道字符串的数字部分是否是连续的.现在,当我像1234 1236 1235 1238这样的内注时,我会做类似下面的事情

            std::vector<int> sortedDigits{1234 1235 1236 1238};
            int count = 1;
            int pos = 0;
            std::vector<std::pair<int, int> > myVec;
            myVec.push_back(std::make_pair(sortedDigits[pos], count));
            for(size_t i = 1; i < sortedDigits.size(); ++i)
            {
                if(sortedDigits[i] != (sortedDigits[i-1] + 1))
                {
                   count = 1;
                   myVec.push_back(std::make_pair(sortedDigits[i], count) );
                   ++pos;
                }
                else
                {
                    sortedDigits[pos].second = ++count;
                }
            }  
Run Code Online (Sandbox Code Playgroud)

所以在最后我得到(1234, 3)(1238, 1)

当字符串出现时,我不知道怎样才能得到这样的东西?

Ker*_* SB 11

由于数字的字符编码值的排序顺序与它们所代表的数字相同,因此您可以对最后四位数进行字符串比较:

#include <cstring>
#include <string>

// Requires: a.size() >= 2, b.size() >= 2
bool two_less(std::string const & a, std::string const & b)
{
    return std::strcmp(a.data() + 2, b.data() + 2) < 0;
}
Run Code Online (Sandbox Code Playgroud)

现在使用sort谓词:

#include <algorithm>
#include <vector>

std::vector<std::string> data { "7X1234", "YX1236" };

std::sort(data.begin(), data.end(), two_less);
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,特别是如果你没有重复使用它,你也可以在sort调用中直接使用lambda :

std::sort(data.begin(), data.end(),
         [](std::string const & a, std::string const & b)
         { return std::strcmp(a.data() + 2, b.data() + 2) < 0; });
Run Code Online (Sandbox Code Playgroud)

然后,如果需要改变它,您甚至可以将数字"2"设为捕获的变量.