PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] How to get value from a vector by value from another vector?

 November 05, 2022     c++, c++11, lambda, this     No comments   

Issue

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.


Solution

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


Answered By - Ben Voigt
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing