分类包含数字和单词的字符串向量
Sorting vectors of string containing both numbers and words
我有一个字符串的向量,包含数字,后跟单词:
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); })
将两个字符串转换为int
(std::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
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值