BlueTrin
BlueTrin

Reputation: 10063

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

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

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

Upvotes: 4

Views: 298

Answers (4)

lsalamon
lsalamon

Reputation: 8174

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 );
}

Upvotes: 0

ronag
ronag

Reputation: 51255

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.

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409166

The simplest I can think about at the moment 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);

Upvotes: 1

Tristram Gr&#228;bener
Tristram Gr&#228;bener

Reputation: 9711

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

Upvotes: 6

Related Questions