In C ++, how do you get an iterator over the second element of a pair vector

I have std::vector<std::pair<int,double>> , is there a quick way in terms of code length and speed:

  • a std::vector<double> for the second element
  • a std::vector<double>::const_iterator for the second element without creating a new vector

I could not find a similar question in the list of questions highlighted when entering the question.

+4
source share
4 answers

For the first question, you can use transform (with lambda from C ++ 11 in my example below). On the second question, I don’t think you can have it.

 #include <vector> #include <string> #include <algorithm> #include <iostream> int main(int, char**) { std::vector<std::pair<int,double>> a; a.push_back(std::make_pair(1,3.14)); a.push_back(std::make_pair(2, 2.718)); std::vector<double> b(a.size()); std::transform(a.begin(), a.end(), b.begin(), [](std::pair<int, double> p){return p.second;}); for(double d : b) std::cout << d << std::endl; return 0; } 
+6
source

I think you want something like:

 std::vector<std::pair<int,double>> a; auto a_it = a | boost::adaptors::transformed([](const std::pair<int, double>& p){return p.second;}); 

Which will create a conversion iterator over the container (iteration to double) without creating a copy of the container.

+6
source

The simplest that I can think of now would be something like:

 std::vector<std::pair<int, double>> foo{ { 1, 0.1 }, { 2, 1.2 }, { 3, 2.3 } }; std::vector<double> bar; for (auto p : foo) bar.emplace_back(p.second); 
+1
source

My way:

 std::pair<int,double> p; std::vector<std::pair<int,double>> vv; std::vector<std::pair<int,double>>::iterator ivv; for (int count=1; count < 10; count++) { p.first = count; p.second = 2.34 * count; vv.push_back(p); } ivv = vv.begin(); for ( ; ivv != vv.end(); ivv++) { printf ( "first : %d second : %f", (*ivv).first, (*ivv).second ); } 
0
source

Source: https://habr.com/ru/post/1432701/


All Articles