Home > OS >  How to get value from a vector by value from another vector?
How to get value from a vector by value from another vector?

Time:05-26

I have two vectors:

one contains numbers and names of things;

second collects numbers that have already been showed to the user;

I'm trying to make a history list of all objects that have been shown.

Here is my code:

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);
    }
};

There is an error:

error: 'this' cannot be implicitly captured in this context
         std::pair<int,std::string> tempPair = paletts[tmp];

I can't make a third vector with the list that is created already. I need to make it by calling a function and printing at the time.

CodePudding user response:

The lambda must capture this to be able to access member variables:

auto  printHist = [this](int& i){ ... };

CodePudding user response:

for_each and lambda are just making your life difficult. The simpler code is explicit iteration:

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?
    }
}
  • Related