C++这个和常量对象



你能告诉我为什么这个代码有效吗?replace_if算法使用了重载运算符()。在主函数中,我创建了IsEqual类的常量对象,所以只应使用常量函数成员。不知怎的,恒常性不起作用,那个操作符被调用了。

#include <iostream>
#include <vector>
#include <algorithm>
class IsEqual {
    int value;
public:
    IsEqual(int v) : value(v) {}
    bool operator()(const int &elem){
    this->value=6;
    return elem == value;
    }
};
int main()
{
    const IsEqual tst(2);
    std::vector<int> vec = {3,2,1,4,3,7,8,6};
    std::replace_if(vec.begin(), vec.end(), tst, 5);
    for (int i : vec) std::cout << i << " ";
    std::cout<<std::endl;
}

结果:3 2 1 4 3 7 8 5

std::replace_if将自己复制tst对象。不需要将其限制为const

如果要在算法中使用原始对象,可以使用std::reference_wrapper。由于它将引用const对象,这将导致编译器错误,因为它要求运算符为const:

std::replace_if(vec.begin(), vec.end(), std::ref(tst), 5);

最新更新