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

标签 c++ templates

错误信息: "二进制 '==': 未找到接受 '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/

相关文章:

c++ - 使用字符串内存

c++ - 如何获得为给定字符手动设置的字形?

c++ - 如何允许模板函数具有 friend(-like) 访问权限?

c++ - 指向类型名成员的指针

c++ - 在 C++ 的非模板类中有一个成员模板函数好吗?

c++ - 尽管文件确实存在,std::filesystem::exists() 返回 false

c++ - GL_QUADS 的 Opengl 纹理映射,得到奇怪的结果

android - 将 Mat 对象从 android java 传递到 native cpp 部分

c++ - 模板类根据其他类的存在和优先级以及更多类型限制(如 const 和区分大小写)调用其他类的某些函数

python - WTForms - 显示属性值而不是 HTML 字段