Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::transform vector of pairs->first to new vector

Tags:

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.

like image 958
justik Avatar asked Feb 01 '12 10:02

justik


People also ask

How do you declare a vector vector of a pair in C++?

Here you go: #include <utility> vector<pair<int, int>> myVec (N, std::make_pair(-1, -1));

How do you find the first element of a vector pair?

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.

How do you declare a 2D vector of pairs in C++?

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.


2 Answers

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.

like image 173
Frerich Raabe Avatar answered Oct 12 '22 15:10

Frerich Raabe


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; });
like image 33
stefaanv Avatar answered Oct 12 '22 15:10

stefaanv