我有一个元组列表,需要从列表中删除元素,如下所示:
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);
}
}表达式:无法增加值初始化列表迭代器
发布于 2019-03-31 05:33:12
首先,,您不想做这个。在基于范围的list中从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
}或者是一个
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
} 有用的补充读物:
擦除成语可以用来解决类似的问题。
https://stackoverflow.com/questions/55438034
复制相似问题