Ann*_*nna 2 c++ lambda this c++11
我有两个向量:
一个包含事物的数字和名称;
第二个收集已经向用户显示的数字;
我正在尝试制作已显示的所有对象的历史列表。
这是我的代码:
class palettArchive{
private:
std::vector<std::pair<int,std::string>> paletts;
int palletsCounter;
std::vector<int> choosen;
public:
//...
void history(){
auto printHist = [](int& i){
int tmp = i;
std::pair<int,std::string> tempPair = paletts[tmp];
std::cout << tempPair.first << " " << tempPair.second;
return 0;
};
std::for_each(choosen.begin(), choosen.end(), printHist);
}
};
Run Code Online (Sandbox Code Playgroud)
有一个错误:
class palettArchive{
private:
std::vector<std::pair<int,std::string>> paletts;
int palletsCounter;
std::vector<int> choosen;
public:
//...
void history(){
auto printHist = [](int& i){
int tmp = i;
std::pair<int,std::string> tempPair = paletts[tmp];
std::cout << tempPair.first << " " << tempPair.second;
return 0;
};
std::for_each(choosen.begin(), choosen.end(), printHist);
}
};
Run Code Online (Sandbox Code Playgroud)
我无法用vector已经创建的列表创建第三个。我需要通过调用函数并当时打印来完成。
lambda必须捕获this才能访问成员变量:
auto printHist = [this](int& i){ ... };
Run Code Online (Sandbox Code Playgroud)