gpt4 book ai didi

c++ - 模板函数中的 `std::remove` 导致 `vector.begin()` 为 `const` 的问题

转载 作者:行者123 更新时间:2023-12-05 00:43:00 25 4
gpt4 key购买 nike

错误信息:"二进制 '==': 未找到接受 'const _Ty' 类型的左操作数的运算符(或没有可接受的转换)"

这个错误似乎是因为我给 std::remove 一个 const 值作为第一个参数,但我不知道 到底是如何v.begin() 不可修改会导致问题,也不知道为什么仅当 vector 的类型是模板化时才会出现此错误,而不是已知类型的 vector 。

模板函数:

// Erases a every element of a certain value from a vector
template <typename T>
std::vector<T> eraseElement(std::vector<T> v, T elem)
{
typename std::vector<T>::iterator newEnd = std::remove(v.begin(), v.end(), elem);
v.erase(newEnd, v.end());
return v;
}

我调用模板函数的方式示例:

struct exampleStruct
{
int x;
}

std::vector<exampleStruct> v;
exampleStruct elem;
elem.x = 2451;
v.push_back(elem);

v = eraseElement(v, elem);

最佳答案

nor why this error only occurs if the type of the vector is templated, as opposed to a known type vector.

also occurs如果您手动替换 exampleStruct

std::vector<exampleStruct> eraseElement(std::vector<exampleStruct> v, exampleStruct elem)
{
auto newEnd = std::remove(v.begin(), v.end(), elem);
v.erase(newEnd, v.end());
return v;
}

这是因为 exampleStruct 没有 operator==。你可能想要类似的东西

bool operator==(const exampleStruct & lhs, const exampleStruct & rhs)
{
return lhs.x == rhs.x;
}

或使用 C++20 实现

struct exampleStruct 
{
int x;
friend bool operator==(const exampleStruct &, const exampleStruct &) = default;
};

关于c++ - 模板函数中的 `std::remove` 导致 `vector.begin()` 为 `const` 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71826513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com