Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a similar way to read integer pairs from stdin to vector<pair<int,int> > in C++

Tags:

c++

I am wondering if there is a way as slick as the following

copy(istream_iterator<int>(cin), istream_iterator<int>(),back_inserter(v));

to copy pairs of int into a vector<pair<int,int> > when the input is given in pairs in the order of their appearance?

Thanks.

like image 514
Qiang Li Avatar asked Jan 25 '11 21:01

Qiang Li


People also ask

How to access values from vector pair in c++?

Basic of Pair in C++ Pair is a container that stores two data elements in it. 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.

How to access first element in pair of vector in c++?

Case 1 : Sorting the vector elements on the basis of first element of pairs in ascending order. This type of sorting can be achieved using simple “ sort() ” function.

How do you fill a pair in C++?

vector<pair<int,int>> moves; pair<int,int> aPair; aPair. first = -2; aPair. second = -1; moves. push_back(aPair); aPair.


2 Answers

boost::zip_iterator could be used.

copy(boost::make_zip_iterator(
         boost::make_tuple(istream_iterator<int>(cin),
                           istream_iterator<int>(cin)),
     boost::make_zip_iterator(
         boost::make_tuple(istream_iterator<int>(),
                           istream_iterator<int>()),
     back_inserter(v));
like image 153
ephemient Avatar answered Nov 02 '22 06:11

ephemient


You can do this – but you need to write your own operator >> for the pair class first. This operator is the whole secret of the above call. Its actual implementation depends on the format of your int pairs.

like image 28
Konrad Rudolph Avatar answered Nov 02 '22 06:11

Konrad Rudolph