从std :: vector <std :: vector <t>&gt; </std :: vector <t>中删除任意项目列表

时间:2014-04-10 16:30:42

标签: c++ c++11 vector move-semantics erase-remove-idiom

我有一个矢量矢量,代表一个数组。我想有效地删除行,即具有最小的复杂性和分配

我考虑过构建一个新的向量向量,只使用移动语义复制未删除的行,如下所示:

    //std::vector<std::vector<T> > values is the array to remove rows from
    //std::vector<bool> toBeDeleted contains "marked for deletion" flags for each row

    //Count the new number of remaining rows
    unsigned int newNumRows = 0;
    for(unsigned int i=0;i<numRows();i++)
    {
        if(!toBeDeleted[i])
        {
            newNumRows++;
        }
    }


    //Create a new array already sized in rows
    std::vector<std::vector<T> > newValues(newNumRows);

    //Move rows
    for(unsigned int i=0;i<numRows();i++)
    {
        if(!toBeDeleted[i])
        {
            newValues[i] = std::move(values[i]);
        }
    }

    //Set the new array and clear the old one efficiently
    values = std::move(newValues);

这是最有效的方法吗?

编辑:我只是想通过迭代地移动行来避免分配新数组,这可能会稍微提高效率并且代码更加简单:

    unsigned int newIndex = 0;
    for(unsigned int oldIndex=0;oldIndex<values.size();oldIndex++)
    {
        if(!toBeDeleted[oldIndex])
        {
            if(oldIndex!=newIndex)
            {
                values[newIndex] = std::move(values[oldIndex]);
            }

            newIndex++;
        }
    }
    values.resize(newIndex);

谢谢!

1 个答案:

答案 0 :(得分:2)

这可以使用通常erase-remove idiom的变体来解决,std::remove_if内的lambda查找迭代器范围内当前行的索引将被删除索引:

#include <algorithm>    // find, remove_if
#include <iostream>
#include <vector>

template<class T>
using M = std::vector<std::vector<T>>; // matrix

template<class T>
std::ostream& operator<<(std::ostream& os, M<T> const& m)
{
    for (auto const& row : m) {
        for (auto const& elem : row)
            os << elem << " ";
        os << "\n";
    }
    return os;
}

template<class T, class IdxIt>
void erase_rows(M<T>& m, IdxIt first, IdxIt last)
{
    m.erase(
        std::remove_if(
            begin(m), end(m), [&](auto& row) {
            auto const row_idx = &row - &m[0];
            return std::find(first, last, row_idx) != last;
        }), 
        end(m)
    );
}

int main()
{
    auto m = M<int> { { 0, 1, 2, 3 }, { 3, 4, 5, 6 }, { 6, 7, 8, 9 }, { 1, 0, 1, 0 } };
    std::cout << m << "\n";

    auto drop = { 1, 3 };
    erase_rows(m, begin(drop), end(drop));

    std::cout << m << "\n";
}

Live Example

注意:因为从C ++ 11开始,std::vector具有移动语义,使用简单的指针操作完成std::vector<std::vector<T>>中的行的移动,无论您的类型如何T(如果你想要 -deletion,那就完全不同了!)。

相关问题