liquid
liquid

Reputation: 111

Removing items from vector string C++

I have a vector, it's contents are like so..

std::vector<string> vec;

vec.push_back("XXXX_LLLL");
vec.push_back("XXXX_HHHH");
vec.push_back("XXXX_XXXX");

I'd like to iterate over the vector and remove the "_" from the string. I've tried using the find-erase idiom as so, with a struct I made to find _.

vec.erase(remove_if(vec.begin(), vec.end(), IsUnderScore2()),vec.end());

But I realized it's not iterating over each individual string in my vector string, so it will never erase the underscore. Is there another method of iterating over a vector, and it's individual components, that can help me here?

Upvotes: 0

Views: 217

Answers (3)

Nikos Athanasiou
Nikos Athanasiou

Reputation: 31489

Using regular expressions would look like :

for_each(vec.begin(), vec.end(), [&](string &str) {
    regex_replace(str.begin(), str.begin(), str.end(), regex("_"), "");
});

Demo

A range based for loop version might be more readable :

for(auto &str : vec) {
    regex_replace(str.begin(), str.begin(), str.end(), regex("_"), "");
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

Try the following. You can use standard algorithm std::remove applied to each string of the vector.

#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;
}

The output is

XXXXLLLL
XXXXHHHH
XXXXXXXX

If your compiler does not support the C++ 2011 then you can write

#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;
}

Upvotes: 4

Praetorian
Praetorian

Reputation: 109119

Iterate through the vector and use the erase-remove idiom on each string, instead of on the vector elements as you're doing right now

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 version:

for(std::vector<std::string>::iterator it = vec.begin(), it != vec.end(), ++it) {
  it->erase(std::remove(it->begin(), it->end(), '_'), 
            it->end());
}

Upvotes: 7

Related Questions