简体   繁体   English

如何在字符向量的向量中使用 copy_if - C++

[英]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 .我有一个vector<vector<char>>并且我正在尝试使用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>> .但我不知道如何在vector<vector<char>>上使用它。

I have a 5 x 5 vector<vector<char>>我有一个 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>> .我试图将所有不是 'x' 的字符复制到一个新的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');});
    }
}

The problem with using copy_if in this situation is that you still want an insertion into the vector even when c is 'x'.在这种情况下使用copy_if的问题是,即使c是“x”,您仍然希望插入向量。 The second problem is that this will not push_back the element into the vector.第二个问题是,这不会push_back元件到载体中。 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.您可以通过将std::back_inserter用于输出迭代器来解决第二个问题,但您仍然需要不同的 std 算法。 However I think this is making things overly complicated when a simple for loop is much clearer:但是,我认为当简单的 for 循环更加清晰时,这会使事情变得过于复杂:

    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 https://gcc.godbolt.org/z/Pcc84o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM