分类包含数字和单词的字符串向量

Sorting vectors of string containing both numbers and words

本文关键字:字符串 向量 单词 包含 数字 分类      更新时间:2023-10-16

我有一个字符串的向量,包含数字,后跟单词:

vector<string> title
{
202 Physics
101 Math
303 Chemistry
}

我想以两种方式对它们进行分类:首先以升数(即101个数学,202个物理学,303化学)和第二个字母/单词(即303 Chemistry,101 Math,202 Physics)的第二名。

我想到的解决方案是使用struct并读取该字符串向量的所有条目中的结构向量,然后对它们进行排序。

但是,这是针对要求我专门与字符串向量合作的学校任务。如何以上述两种方式对字符串的向量进行分类?

std::sort允许可选比较器。简单的lambda功能使您可以执行基本的操作,以根据字符串的不同组件进行比较。这是一个非常简单的最小示例,假定课程编号总是长三位数,其次是一个空间,因此您可以将std::stoi用于数字比较,而substr方法进行课程标题比较:

int main()
{
    std::vector<std::string> title{"202 Physics"s, "101 Math"s, "303 Chemistry"s};
    std::sort(title.begin(), title.end(), [](const auto& a, const auto &b) { return std::stoi(a) < std::stoi(b); });
    std::cout << "By number" << std::endl;
    for (auto&& s : title) {
        std::cout << s << std::endl;
    }

    std::sort(title.begin(), title.end(), [](const auto& a, const auto &b) { return a.substr(4) < b.substr(4); });
    std::cout << std::endl << "By title" << std::endl;
    for (auto&& s : title) {
        std::cout << s << std::endl;
    }
    return 0;
}

在线尝试!

在每种情况下,当左元素小于右时,比较器都会返回true,因此[](const auto& a, const auto& b) { return std::stoi(a) < std::stoi(b); })将两个字符串转换为intstd::stoi在课程编号后击中非数字空格字符时停止处理)并进行比较,并进行比较,当[](const auto& a, const auto &b) { return a.substr(4) < b.substr(4); }切片每个字符串的前四个字符,仅留下课程标题,并比较其余的。

按第一个数字数字进行排序,然后按第一个字母char排序。没有假设第一个数字数字和第一个字母char位于字符串中(只要存在)。但确实假定所有数字都具有相同数量的数字。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<string> vec{"202 Physics","101 Math","303 Chemistry"};
    cout << "Originaln";
    for (auto item : vec)
      std::cout << item << " ";
    cout << std::endl;

    cout << "Sort by first digitn";
    std::sort(std::begin(vec ), std::end(vec ), [](string a, string b) 
    {return *find_if(a.begin(), a.end(), [](char c){return isdigit(c);}) 
          < *find_if(b.begin(), b.end(), [](char c){return isdigit(c);}); });
    for (auto item : vec)
      std::cout << item << " ";
    cout << std::endl;

    cout << "Sort by first alphabetical charn";
    std::sort(std::begin(vec ), std::end(vec ), [](string a, string b) 
    {return *find_if(a.begin(), a.end(), [](char c){return isalpha(c);}) 
          < *find_if(b.begin(), b.end(), [](char c){return isalpha(c);}); });
    for (auto item : vec)
      std::cout << item << " ";
    cout << std::endl;    
}

产生输出:

Original
202 Physics 101 Math 303 Chemistry 
Sort by first digit
101 Math 202 Physics 303 Chemistry 
Sort by first alphabetical char
303 Chemistry 101 Math 202 Physics