One liner for inserting some particular value of class object

  • A+

Suppose I have a vector<int> myVec; and I want to convert it to a set, I can have a one liner-

set<int> mySet(myVec.begin(), myVec.end()); 

This is something that can be found easily.

Now I have vector<pair<int, int>>, and I want to obtain the set of the second values in each of the pairs. How should I use a set constructor to achieve this? Is it possible?

Assuming I have C++11, C++14, C++17.

Also, I would appreciate if I can get some information about how to do similar tweaks in a general sense for different containers.


This almost-one-liner should work for you:

#include <algorithm> #include <iterator> #include <iostream> #include <set> #include <utility> #include <vector>  int main() {     std::vector<std::pair<int, int>> myVec = { {1, 2}, {3, 4} };     std::set<int> mySet;     std::transform(myVec.begin(), myVec.end(), std::inserter(mySet, mySet.begin()),                    [](const std::pair<int, int>& elem) { return elem.second; });     for (int value : mySet)     {         std::cout << value << std::endl;     }     return 0; } 


2 4 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: