繁体   English   中英

从std :: list中删除std :: tuple

[英]Removing std::tuple from std::list

我有一个元组列表,需要从列表中删除元素,如下所示:

enum class test
{
    mem1,
    mem2,
    mem3,
    mem4
};

struct A
{

};

int main()
{
    std::list<std::tuple<int, test, A>> tuple_list;

    // fill list with random objects
    for (int i = 0; i < 4; i++)
    {
        tuple_list.push_back(
               std::forward_as_tuple(i, static_cast<test>(i), A()));
    }

    // now remove it
    for (auto& ref : tuple_list)
    {
        tuple_list.remove(ref); // error C2678
    }
    return 0;
}

错误C2678:二进制'==':找不到哪个运算符带有'const _Ty'类型的左操作数(或者没有可接受的转换)

如何从上面的示例中的列表中删除元组元素?

编辑:

我尝试了以下方法,它编译得很好,不像以前的例子,但有运行时断言:

int main()
{
    list<tuple<int, test, A>> tuple_list;

    for (int i = 0; i < 4; i++)
    {
        tuple_list.push_back(
                std::forward_as_tuple(i, static_cast<test>(i), A()));
    }

    for (auto iter = tuple_list.begin(); iter != tuple_list.end(); iter++)
    {
        tuple_list.erase(iter);
    }
}

表达式:无法递增值初始化列表迭代器

首先, 你不想这样做 从删除的项目list中的中间(或任何容器)范围为基础for是一个灾难的背后隐藏着for循环是迭代器 ,将尽快项被删除无效。

这与第二次实验的问题相同

for (auto iter = tuple_list.begin(); iter != tuple_list.end(); iter++)
{
    tuple_list.erase(iter); // iter rendered invalid. 
                            // That makes iter++ and iter != tuple_list.end()
                            // totally bogus.
}

这个版本可以修复

for (auto iter = tuple_list.begin(); iter != tuple_list.end(); /* nothing here */)
{
    iter = tuple_list.erase(iter); // iter updated here
}

或者a

while (! tuple_list.empty()) 
{
     tuple_list.pop_front();
}

要么

tuple_list.clear();

好。 到底出了什么问题:

错误C2678:二进制'==':找不到哪个运算符带有'const _Ty'类型的左操作数(或者没有可接受的转换)

表示无法比较元组的其中一个部分是否相等。

struct A
{

};

没有相等的运算符。 解决方案是添加一个。

struct A
{
}; 

bool operator==(const A& lhs, const A& rhs)
{ 
    Comparison logic goes here 
}    

有用的额外阅读:

擦除删除成语可用于解决类似问题。

暂无
暂无

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

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