#include <vector>
///CopyFirst copies the first std::pair elements from a std::vector of std::pairs
//From http://www.richelbilderbeek.nl/CppCopyFirst.htm
template <class T, class U>
const std::vector<T> CopyFirstFor(const std::vector<std::pair<T,U> >& v)
{
std::vector<T> w;
const int size = static_cast<int>(v.size());
for (int i=0; i!=size; ++i)
{
w.push_back(v[i].first);
}
return w;
}
///CopySecond copies the second std::pair elements from a std::vector of std::pairs
//From http://www.richelbilderbeek.nl/CppCopySecond.htm
template <class T, class U>
const std::vector<U> CopySecondFor(const std::vector<std::pair<T,U> >& v)
{
std::vector<U> w;
const int size = static_cast<int>(v.size());
for (int i=0; i!=size; ++i)
{
w.push_back(v[i].second);
}
return w;
}
#include <algorithm>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
///CopyFirst copies the first std::pair elements from a std::vector of std::pairs
//From http://www.richelbilderbeek.nl/CppCopyFirst.htm
template <class T, class U>
const std::vector<T> CopyFirst(const std::vector<std::pair<T,U> >& v)
{
std::vector<T> w;
std::transform(
v.begin(),
v.end(),
std::back_inserter(w),
boost::lambda::bind(&std::pair<T,U>::first, boost::lambda::_1)
);
return w;
}
///CopySecond copies the second std::pair elements from a std::vector of std::pairs
//From http://www.richelbilderbeek.nl/CppCopySecond.htm
template <class T, class U>
const std::vector<U> CopySecond(const std::vector<std::pair<T,U> >& v)
{
std::vector<U> w;
std::transform(
v.begin(),
v.end(),
std::back_inserter(w),
boost::lambda::bind(&std::pair<T,U>::second, boost::lambda::_1)
);
return w;
}
#include <cassert>
#include <string>
int main()
{
//C++11 initializer list
const std::vector<std::pair<int,std::string> > v
= { {0,"Zero"}, {1,"One"}, {2,"Two"}, {3,"Three"}, {4,"Four"} };
{
const std::vector<int> w1 = CopyFirstFor(v);
const std::vector<int> w2 = CopyFirst(v);
const std::vector<int> expected = { 0,1,2,3,4 };
assert(w1 == expected);
assert(w2 == expected);
}
{
const std::vector<std::string> w1 = CopySecondFor(v);
const std::vector<std::string> w2 = CopySecond(v);
const std::vector<std::string> expected
= { "Zero", "One", "Two", "Three", "Four" };
assert(w1 == expected);
assert(w2 == expected);
}
}
|