从vector字符串中删除项
Removing items from vector string C++
我有一个向量,它的内容是这样的…
std::vector<string> vec;
vec.push_back("XXXX_LLLL");
vec.push_back("XXXX_HHHH");
vec.push_back("XXXX_XXXX");
我想迭代向量并从字符串中删除"_"。我已经尝试过使用查找-擦除习惯用法,我创建了一个结构体来查找_.
vec.erase(remove_if(vec.begin(), vec.end(), IsUnderScore2()),vec.end());
但是我意识到它不会迭代向量字符串中的每个字符串,所以它永远不会删除下划线。有没有另一种迭代向量的方法,以及它的独立分量,这对我有帮助?
遍历vector
并在每个字符串上使用擦除习惯用法,而不是像现在这样在vector
元素上使用
std::vector<string> vec;
vec.push_back("XXXX_LLLL");
vec.push_back("XXXX_HHHH");
vec.push_back("XXXX_XXXX");
for(auto& str : vec) {
str.erase(std::remove(str.begin(), str.end(), '_'),
str.end());
}
c++ 03版:
for(std::vector<std::string>::iterator it = vec.begin(), it != vec.end(), ++it) {
it->erase(std::remove(it->begin(), it->end(), '_'),
it->end());
}
尝试以下操作。您可以使用标准算法std::remove
应用于向量的每个字符串。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> vec;
vec.push_back("XXXX_LLLL");
vec.push_back("XXXX_HHHH");
vec.push_back("XXXX_XXXX");
for ( std::string &s : vec )
{
s.erase( std::remove( s.begin(), s.end(), '_'), s.end() );
}
for ( const std::string &s : vec ) std::cout << s << std::endl;
return 0;
}
输出为
XXXXLLLL
XXXXHHHH
XXXXXXXX
如果你的编译器不支持c++ 2011,那么你可以写
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> vec;
vec.push_back("XXXX_LLLL");
vec.push_back("XXXX_HHHH");
vec.push_back("XXXX_XXXX");
for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it )
{
it->erase( std::remove( it->begin(), it->end(), '_'), it->end() );
}
for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it )
{
std::cout << *it << std::endl;
}
return 0;
}
使用正则表达式看起来像:
for_each(vec.begin(), vec.end(), [&](string &str) {
regex_replace(str.begin(), str.begin(), str.end(), regex("_"), "");
});
基于范围的for循环版本可能更具可读性:
for(auto &str : vec) {
regex_replace(str.begin(), str.begin(), str.end(), regex("_"), "");
}
相关文章:
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 删除字符串后C++检测到堆损坏
- 如何在 c++ 中删除字符串中的某些字符?
- 删除字符串数组
- 删除字符串中具有相同值的任何相邻字母"pair"
- 删除字符串向量中的字符重复
- 如何在Qt中删除字符串(qstring)中的子字符串
- 删除字符串指针在struct中的内存
- 删除 C 字符串中的大写字母
- 如何搜索和删除字符串中的字符
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 删除字符串中不平衡的括号
- 删除字符串数组中的换行符
- 如何修复我的代码以删除字符串中的空格
- 如何删除字符串所有可能的子字符串中带有空格的子字符串?
- 如何创建删除 C 字符串中所有选定字符的函数
- 传递GTK回调时,请在C 中删除字符串向量
- 为什么删除字符串迭代器会产生const char参考
- 从<string>向量<int>中定义的索引处的向量中删除字符串
- 如何使用 c++ 剪切或删除字符串中的某些字符