Astoria
Astoria

Reputation: 23

How to access pairs in C++?

I don't know how to name this question more properly, but this is it, basically:

I've made a pair pair<int, int> P[20000] and I'm using P.first and P.second but...

When I try to input into P.first, like cin >> P.first[i] (i is the counter) it doesn't let me. It calls an error when compiling. How do I fix this?

Edit: Got the answer to my previous question, but new question: I'm trying to run a descending sort on P.second like so

sort(P.second, P.second + x, greater<int>());

but it causes another compilation error. I understand why this happens, but how do I fix it. Basically, say that the pairs are {{0,0}, {3,2}, {4,-1}, {5,1}} my desired result is {{3,2}, {5,1}, {0,0}, {4,-1}}.

How would I go about doing this?

Upvotes: 0

Views: 1090

Answers (3)

cse
cse

Reputation: 4104

The indexing is wrong in your code.
To correct it, use cin>>P[i].first instead of cin>>P.first[i].

To sort your entries, use std:sort as following:

using Pair = std::pair<int, int>;
auto&& comparator =  [](const Pair& lhs, const Pair& rhs){ return lhs.second > rhs.second;};
std::sort( P, P + 20000, comparator );

See here for more information about std::pair and here for more information about std::sort.

Note: You will need to include <algorithm> header file to use std:sort function.

Visit here to see an working example.

Upvotes: 11

Binghe Zhai
Binghe Zhai

Reputation: 93

answer to second question:

//if you want sort P[] by using first as primiry key and second as second key
std::sort(P, P + 20000, std::greater<std::pair<int, int>>());
//if you wang sort p[] by second only
typedef std::pair<int, int> IIPair;
std::sort(P, P + 20000, [](const IIPair &lhs, const IIPair &rhs){ return lhs.second > rhs.second;});

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66371

Since P is an array of pairs, its elements P[i] are pairs.
Since P[i] is a pair, you can access its parts with P[i].first and P[i].second.

Upvotes: 0

Related Questions