加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C这和恒定的对象

发布时间:2020-12-16 03:28:56 所属栏目:百科 来源:网络整理
导读:你能告诉我为什么这段代码有效吗?有重载的operator()由replace_if算法使用.在main函数中,我创建了IsEqual类的常量对象,因此只应使用常量函数成员.某种程度上,constancy不起作用,并且该运算符被调用. #include iostream#include vector#include algorithmcla
你能告诉我为什么这段代码有效吗?有重载的operator()由replace_if算法使用.在main函数中,我创建了IsEqual类的常量对象,因此只应使用常量函数成员.某种程度上,constancy不起作用,并且该运算符被调用.
#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(),std::ref(tst),5);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读