Re: Splitting vector<pair<int,int> > to pair<vector<int>,vector<int> >
Richard Powell wrote:
What would be the most effective way to convert vector<pair<int,int> >
to pair<vector<int>,vector<int> >?
I know I can do it as follows:
struct split : unary_function<void, pair<int,int> >
{
pair<vector<int>,vector<int> > a;
void operator()(pair<int,int> p) { a.first.push_back(p.first);
a.second.push_back(p.second); }
};
...
vector<pair<int,int> > p;
for (int i = 0; i < 100; i++)
p.push_back(pair<int,int>(i,2*i));
split s = for_each(p.begin(), p.end(), split());
...
But I'm not very satisfied with that solution. It seems that I'll
need to have 3 vectors at the end of the day, 1 of the original, and 2
afterwards.
Um, yes? If I'm not misunderstanding you, that is exactly what you need,
rigth? Or is it just that you don't need the original afterwards? In that
case, I'd say that you are making some premature optimisations.
Anyway, I would write two functors, select_first and select second and then
use std::transform:
// Note: I'm not sure about the parameter ordering here
transform( p.begin(), p.end,
back_inserter(target.first), select_first());
transform( p.begin(), p.end,
back_inserter(target.second), select_second());
Is there a better way?
Define "better". Anyway, the fastest operation is the one that you don't do,
i.e. if you have settled on an (abstract) interface you simply program it
in a way that doesn't involve shifting data around, i.e. you write a
wrapper that feels like a std::vector but internally operates on the first
or second of a vector of pairs.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]