gpt4 book ai didi

c++ - 使用排序和函数对象,但函数对象不能修改成员变量

转载 作者:行者123 更新时间:2023-11-28 05:01:43 24 4
gpt4 key购买 nike

我写的代码如下,不知道为什么排序后成员变量flag不等于1?有人可以给我建议吗。

代码:

class Func{
public:
int flag;
Func()
{
flag = 0;
}
bool operator()(int &l, int &r)
{
if(l==r)
{
flag = 1;
}
return l > r;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
vector<int> a;
int b[] = {11,8,7,6,4,3,4,1};
for(int i = 0; i <sizeof(b)/sizeof(b[0]); i++)
{
a.push_back(b[i]);
}

Func FuncObj = Func();
std::sort(begin(a), end(a), FuncObj);
return 0;
}

最佳答案

According to reliable documentation , std::sort 按值接受函数对象。这意味着 std::sort 使用的 FuncFuncObj 的拷贝。这意味着当 4 与 4 进行比较时,拷贝的 flag 变量设置为 1,而 FuncObj 不变。当 std::sort 返回时拷贝被销毁,所以这个 flag 丢失了。

最简单的解决方案是将 int flag 定义为 static int flag 以便 Func 的所有实例共享相同的 Flag.

如果这不是一个选项,不同的 Func 必须有自己的 flag,我倾向于使用 std::shared_ptr .每个默认构造的 Func 都有它自己的 flag 并与任何拷贝共享这个 flag

但是本杰明·林德利让我们想起了 std::reference_wrapper这为问题提供了更方便的解决方案。包装器按值传递并复制,而不是复制它引用的 Func,允许在 std::sort 中修改源代码 Func

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

class Func{
public:
int flag;
Func(): flag(0)
{
}
bool operator()(int &l, int &r)
{
if(l==r)
{
flag = 1;
}
return l > r;
}
};

int main()
{
std::vector<int> a = {11,8,7,6,4,3,4,1};

Func FuncObj = Func();
std::sort(begin(a), end(a), std::reference_wrapper<Func>(FuncObj));
std::cout << FuncObj.flag;
return 0;
}

关于c++ - 使用排序和函数对象,但函数对象不能修改成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768345/

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