r8019246
r8019246

Reputation: 49

Initialising a pair of vectors and transforming them

I would like to use a pair of vectors instead of two vectors in my transform functions, but don't know how I could possibly initialise the two vectors inside the make_pair function.

I have the following code and it works fine:

vector<Point> group_pts(size);
vector<int> group_rs(size);

std::transform(group.begin(), group.end(), group_pts.begin(), 
         [](const Circle& c1) -> Point { return c1.p;    } );
std::transform(group.begin(), group.end(), group_rs.begin(), 
         [](const Circle& c1) -> int { return c1.radius; } );
std::pair < vector<Point>, vector<int> > group_dscrp = make_pair(group_pts, group_rs);
return group_dscrp;

But, I need to have something like this but don't know how I should initialise

std::pair < vector<Point>, vector<int> > group_dscrp = INIT;

std::transform(group.begin(), group.end(), group_dscrp.first.begin(), 
              [](const Circle& c1) -> Point { return c1.p; } );

std::transform(group.begin(), group.end(), group_dscrp.second.begin(), 
              [](const Circle& c1) -> int {   return c1.radius; } );

return group_dscrp;

Upvotes: 0

Views: 248

Answers (1)

JeJo
JeJo

Reputation: 33092

The answer to your question is already mentioned in the comments(by @MatthieuBrucher).

std::pair<vector<Point>, vector<int>> group_dscrp{size, size}

will initialize the pair of vectors.

However, if you need a data structure which holds both Point and radius member of the Circle, you may wanna rethink with(as @WhozCraig mentioned)

std::vector<std::pair<Point, int>> group_dscrp

Now you can again either play with the std::transform

std::transform(group.cbegin(), group.cend(), std::back_inserter(group_dscrp), 
    [](const Circle& circle) {return std::pair<Point, int>{ circle.p, circle.radius };  });

or go for a simple range based loop to insert in to the group_dscrp as follows:

std::vector<Circle> group;
std::vector<std::pair<Point, int>> group_dscrp;
group_dscrp.reserve(size);
for (const Circle& circle : group) group_dscrp.emplace_back(circle.p, circle.radius);

Upvotes: 1

Related Questions