gpt4 book ai didi

c++ - 指向 vector 元素的持久指针代替 'this'

转载 作者:行者123 更新时间:2023-11-27 22:38:11 25 4
gpt4 key购买 nike

我需要指向 std::vector 元素的持久指针。简单的 this 不会这样做,如下所示:

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

class A {
public:
A() = delete;
A(int i)
: my_i(i)
, whoAmI([this]()->void{ std::cout<<"I am class A with i="<<my_i<<std::endl; })
{}
A(const A&) = delete;
A(A&&) = default;
int my_i;
std::function<void()> whoAmI;
};

int main()
{
std::vector<A> vec;
std::cout << "Initialization:" << std::endl;
for (int i=0; i<3; ++i) {
vec.push_back(A(i));
vec.back().whoAmI();
}
std::cout << "Retrieval:" << std::endl;
for (int i=0; i<3; ++i)
vec.at(i).whoAmI();
}

哪个产量

Initialization:
I am class A with i=0
I am class A with i=1
I am class A with i=2
Retrieval:
I am class A with i=2
I am class A with i=2
I am class A with i=2

而我需要

Retrieval:
I am class A with i=0
I am class A with i=1
I am class A with i=2

当然,在这个例子中,可以很容易地变通。在现实生活中,持久指针应该传递给Qt::connect

最佳答案

也许尝试像这样按值捕获索引:

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


class A {
public:
A() = delete;
A(int i, std::vector<A> &vec)
: whoAmI([i, &vec]()->void{
std::cout<<"I am class A with i="<< i << ". Calling whoAmI(): " << std::endl;
vec[i];
})
{}
A(const A&) = delete;
A(A&&) = default;
std::function<void()> whoAmI;


};

int main()
{
std::vector<A> vec;
std::cout << "Initialization:" << std::endl;
for (int i=0; i<3; ++i) {
vec.push_back(A(i, vec));
vec.back().whoAmI();
}
std::cout << "Retrieval:" << std::endl;
for (int i=0; i<3; ++i)
vec.at(i).whoAmI();
}

关于c++ - 指向 vector 元素的持久指针代替 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558972/

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