I have a std::vector<std::pair<int,double>>
, is there a quick way in terms of code length and speed to obtain:
std::vector<double>
on the second elementstd::vector<double>::const_iterator
on the second element without creating a new vectorI did not manage to find a similar question in the list of questions highlighted when typing the question.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With