Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

  • a std::vector<double>on the second element
  • a std::vector<double>::const_iteratoron the second element without creating a new vector

I did not manage to find a similar question in the list of questions highlighted when typing the question.

like image 455
BlueTrin Avatar asked Dec 11 '22 22:12

BlueTrin


2 Answers

For the first question, you can use transform (with a lambda from c++11 in my example below). For the second question, i don't think you can have that.

#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;
}
like image 114
Tristram Gräbener Avatar answered Feb 16 '23 00:02

Tristram Gräbener


I think what you want is 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 transform iterator over the container (iterating over doubles), without creating a copy of the container.

like image 23
ronag Avatar answered Feb 15 '23 23:02

ronag