fork(1) download
  1. #include <iostream>
  2. #include <utility>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <iterator>
  6. #include <functional>
  7. using namespace std;
  8.  
  9. int get_first(const std::pair<int, int> p) { return std::get<0>(p); }
  10.  
  11. int main() {
  12. std::vector<int> items;
  13. std::vector<std::pair<int, int>> pairs;
  14.  
  15. pairs.push_back(std::make_pair(1, 3));
  16. pairs.push_back(std::make_pair(5, 7));
  17.  
  18. // With custom function.
  19. std::transform(pairs.begin(), pairs.end(), std::back_inserter(items),
  20. get_first);
  21.  
  22. // With std::get<0>, but this is super nasty. :(
  23. std::transform(pairs.begin(), pairs.end(), std::back_inserter(items),
  24. (const int& (*)(const std::pair<int, int>&))std::get<0>);
  25.  
  26. // With lambda; it's not much better.
  27. std::transform(pairs.begin(), pairs.end(), std::back_inserter(items),
  28. [](const std::pair<int, int>& p) { return std::get<0>(p); });
  29.  
  30. std::copy(items.begin(), items.end(),
  31. std::ostream_iterator<int>(std::cout, " "));
  32. cout << endl;
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
1 5 1 5 1 5