Dev
Dev

Reputation: 3

How to use copy_if in a vector of vector of char - C++

I have a vector<vector<char>> and I am trying to use copy_if. This function requires a begin and an end iterator. I know how to use it on a vector. But I don't have any idea of how to use it on a vector<vector<char>>.

I have a 5 x 5 vector<vector<char>>

'a' 'a' 'x' 'x' 'b'
'a' 'x' 'c' 'c' 'd'
'd' 'd' 'd' 'x' 'b'
'a' 'a' 'x' 'x' 'b'
'a' 'a' 'x' 'x' 'b'

I am trying to copy all of the characters that are not 'x' into a new vector<vector<char>>. So it should look like

'a' ' ' ' ' ' ' 'b'
'a' 'a' ' ' ' ' 'd'
'd' 'd' ' ' ' ' 'b'
'a' 'a' 'c' ' ' 'b'
'a' 'a' 'd' 'c' 'b'

The other characters kind of fall vertically

This is what I have tried:

vector<vector<char>>::iterator row;
vector<char>::iterator col
int i = -1;

for(row = board.begin(); row != board.end(); ++row)
{
    boardCopy.push_back(vector<char>());
    ++i;

    for(col = row->begin(); col != row->end(); ++col)
    {
         copy_if(row->begin(); row->end(), boardCopy[i].begin(), [](char x){return (c != 'x');});
    }
}

Upvotes: 0

Views: 110

Answers (1)

elldur
elldur

Reputation: 2103

The problem with using copy_if in this situation is that you still want an insertion into the vector even when c is 'x'. The second problem is that this will not push_back the element into the vector. It will actually write to the potentially uninitialized memory after the end of the vector.

You can fix the second problem by using std::back_inserter for your output iterator but you still need a different std algorithm. However I think this is making things overly complicated when a simple for loop is much clearer:

    vector<vector<char>> table = { /* characters here */ };
    vector<vector<char>> new_table;

    for (vector<char> const& row : table)
    {
        auto& new_row = new_table.emplace_back();
        for (char c : row)
        {
            if (c != 'x') { new_row.push_back(c); }
        }
        new_row.resize(5, ' ');
    }

https://gcc.godbolt.org/z/Pcc84o

Upvotes: 3

Related Questions