Sorry for a little bit beginner question. There are vector and vector of pairs
typedef std::vector <int> TItems;
typedef std::vector < std::pair <int, int> > TPairs;
Is there any way to transform all first items in pair to another vector in one step
int main ()
{
TItems items;
TPairs pairs;
pairs.push_back (std::make_pair(1,3));
pairs.push_back (std::make_pair(5,7));
std::transform( items.begin(), items.end(), items.begin(), comp ( &pairs ) );
return 0;
}
How to design a functor?
class comp
{
private:
TPairs *pairs;
public:
comp ( TPairs *pairs_ ) : pairs ( pairs_) { }
unsigned int operator () ( const unsigned int index ) const
{
return (*pairs)[index].second != pairs->end(); //Bad idea
}
};
Maybe there is some more user friendly method without lambda expressions and loops. Thanks for your help.
Here you go: #include <utility> vector<pair<int, int>> myVec (N, std::make_pair(-1, -1));
Basic of Pair in C++ It is not necessary that the two values or data elements have to be of the same data type. The first value given in above pair could be accessed by using pair_name. first similarly, the second value could be accessed using pair_name. second.
A 2D vector of pairs or vector of vectors of pairs is a vector in which each element is a vector of pairs itself. Here, dataType1 and dataType2 can be similar or dissimilar data types. Example 1: In the below C++ program, a vector of vectors of pairs of type {int, string} is used.
First of all, you should use a back_inserter
as the third argument to transform
so that the transformed values are pushed to the back of the vector.
Second, you need some sort of functor which takes a pair of ints and returns the first one. This should do:
int firstElement( const std::pair<int, int> &p ) {
return p.first;
}
Now, to put the pieces together:
TPairs pairs;
pairs.push_back( std::make_pair( 1, 3 ) );
pairs.push_back( std::make_pair( 5, 7 ) );
TItems items;
std::transform( pairs.begin(), pairs.end(), std::back_inserter( items ),
firstElement );
After this code, items
contains 1 and 5.
see frerich's or kotlinski's answer for C++03.
C++11 solution with lambda:
std::transform(pairs.begin(),
pairs.end(),
std::back_inserter(items),
[](const std::pair<int, int>& p) { return p.first; });
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