从vector字符串中删除项

Removing items from vector string C++

本文关键字:删除 字符串 vector      更新时间:2023-10-16

我有一个向量,它的内容是这样的…

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("_"), "");
}