STL Pair questions

Jun 21, 2021 at 4:16pm
Hello guys,

I have the three following questions:

1)Suppose we have the following set of pairs (set<pair<int,int>> set_name)
{ (1,10) (2,20) (3,30) (4,20) (5,10) (6,20) (7,30) }

which 1,2,3,... and 10,20,30 are values read from a csv file like the following
1,10
2,20
3,30
4,20
5,10
6,20
7,30

My question is: Is it possible to perform any kind of operation between the first or second between pairs?

i.e for the pairs (3,30) and (7,30) to do 7-3=4 ?

2)Can I sort a vector<pair<string,int>> using STL sort based on the pair's second?

i.e (name1,10)
(name2,30)
(name3,20)

to become
(name1,10)
(name3,20)
(name2,30)

Thank you in advance
Last edited on Jun 21, 2021 at 4:26pm
Jun 21, 2021 at 4:51pm
The answer to both questions is yes, and begins with how you obtain the two entries.

1
2
3
4
5
std::pair<int,int> a { 2, 20 };

int i_f = a.first;
int i_s = a.second; 


This is a simple, old style means of gaining access to the first or second member of a pair.

1
2
3
4
5
std::pair<int,int> a { 2, 20 };
std::pair<int,int> b { 3, 30 };

int x = b.first - a.first;


Now, for sorting I'll leave some of the research up to you. What you need to find and learn is how to supply a custom sorting function to the sort algorithm. A tutorial is beyond the scope of a post here.

However, what I can tell you is that your function (or function object) which compares two entries will receive two const std::pair references (or should) from the source vector (or whatever container you're sorting), and you'll perform a comparison on, say, a.second - where a is the std::pair and you intend to sort on the second partner in the pair.

Now, about the "old style" I show above. Another, newer style (available in more recent C++ versions) is:


 
auto & [ i1, i2 ] = a;


This means that i1 and i2 will be references to the first and second parts of the pair, automatically typed to match the types in the pair.

i1 is the first, i2 is the second.

This is not available to you if your compiler is set to older versions of C++.

Last edited on Jun 21, 2021 at 4:54pm
Jun 21, 2021 at 5:46pm
Is it possible to perform any kind of operation between the first or second between pairs?


You can have an operator overload for the pair type that does what is required. Eg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <utility>
#include <iostream>

using Mypair = std::pair<int, int>;

Mypair operator-(const Mypair& p1, const Mypair& p2) {
	return {p1.first - p2.first, p1.second - p2.second};
}

std::ostream& operator<<(std::ostream& os, const Mypair& p) {
	return os << '(' << p.first << ", " << p.second << ')';
}

int main()
{
	Mypair p1 {3, 30};
	Mypair p2 {7, 30};

	std::cout << p2 - p1 << '\n';
}



(4, 0)


Jun 21, 2021 at 8:24pm
Guys thank you very much for your replies!
Topic archived. No new replies allowed.