我有兩個向量:
一個包含事物的編號和名稱;
第二次收集已經顯示給用戶的號碼;
我正在嘗試制作已顯示的所有物件的歷史串列。
這是我的代碼:
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);
}
};
有一個錯誤:
error: 'this' cannot be implicitly captured in this context
std::pair<int,std::string> tempPair = paletts[tmp];
我不能vector用已經創建的串列來做第三個。我需要通過呼叫一個函式并在當時列印來實作它。
uj5u.com熱心網友回復:
lambda必須捕獲this才能訪問成員變數:
auto printHist = [this](int& i){ ... };
uj5u.com熱心網友回復:
for_each和 lambda 只會讓你的生活變得困難。更簡單的代碼是顯式迭代:
void history()
{
for (auto i : choosen) {
auto tempPair = paletts[i];
std::cout << tempPair.first << " " << tempPair.second;
// did you mean to send a newline "\n" also?
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481814.html
上一篇:為什么char陣列可以是模板引數但constchar*不能
下一篇:迭代器運算子 多載編譯錯誤
