c++ - 如何删除具有特定条件的 vector 中的所有元组?

标签 c++ vector tuples

我有一个带有3个元组的 vector 。我想删除第二个值为4的所有元组。这是我的代码:

int main() {

    tuple thing1 = make_tuple(1, 4, 2, 2);
    tuple thing2 = make_tuple(2, 2, 2, 2);
    tuple thing3 = make_tuple(3, 4, 2, 2);

    vector<thing> things = {thing1, thing2, thing3};

    int index = 0;
    for (vector<thing>::iterator it = things.begin(); it != things.end(); ++it) {
        if (get<1>(*it) == 4) {
            things.erase(things.begin()+index);
        } else {
            index++;
        }
    }
}

但是这段代码删除了所有这些代码。有人可以帮我吗?谢谢你这么糊涂:)

最佳答案

答案来自std::vector removing elements which fulfill some conditions。使用remove_if函数模板,

things.erase(std::remove_if(
things.begin(), things.end(),
[](const thing& x) -> bool{ 
    return get<1>(x) == 4; // put your condition here
}), things.end());

在C++ Shell上查看example

关于c++ - 如何删除具有特定条件的 vector 中的所有元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337911/

相关文章:

c++ - 想要在 C 中使用 while 创建菱形

c++ - 'boost::make_shared':对重载函数的模糊调用

c++ - 通过引用 vector 传递的线程函数启动缓慢

C++:将 vector reshape 为 3D 数组

python - 当 b 是列表时,为什么 b+=(4,) 有效,而 b = b + (4,) 无效?

python - 在 Python 中总结一个列表 - 在一个元组和另一个列表中

C++ iostream 运算符覆盖函数返回类型

c++ - 在堆栈上取消引用变量或最近取消引用的成本?

c++ - 为什么我不能返回这个 vector 的 vector ?

c++ - 如何使用可变模板参数为元组专门化类模板?