beuhbbb
beuhbbb

Reputation: 277

data structure bind conversion c++

I think this is a classical question but I did not manage to find a clear answer (maybe my keywords are not the good one).

Let's say I have a structure of the form (this is a recurrent situation in my programming practice):

std::vector< pair<unsigned int, double> > pairAgeSize;

and I have a function of the form :

double getMean(const std::vector<double> & sample);

What is the "best" way to call getMean on the elements [pairAgeSize[0].first,...,pairAgeSize[n].first] ? or even on [pairAgeSize[0].second,...,pairAgeSize[n].second] ?

More generally, is there any pragmatical practice rules that can prevent this kind of situation ?

Upvotes: 2

Views: 135

Answers (2)

moswald
moswald

Reputation: 11677

If you absolutely can't get rid of getMean (maybe it's a library method you don't have the ability to change):

std::vector<double> justSizes;
std::transform(pairAgeSize.begin(), pairAgeSize.end(), std::back_inserter(justSizes), [](const std::pair<unsigned int, double> &ageSize) { return ageSize.second; });

Upvotes: 1

djechlin
djechlin

Reputation: 60768

getMean should take iterators as inputs to it to be fully general, and you should write a custom iterator that will return pair.first.

Upvotes: 1

Related Questions