C++
std :: pair
Zoeken…
Een paar maken en toegang krijgen tot de elementen
Met Pair kunnen we twee objecten als één object behandelen. Paren kunnen eenvoudig worden gebouwd met behulp van sjabloonfunctie std::make_pair .
Alternatieve manier is om een paar te maken en de elementen ( first en second ) later toe te wijzen.
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> p = std::make_pair(1,2); //Creating the pair
std::cout << p.first << " " << p.second << std::endl; //Accessing the elements
//We can also create a pair and assign the elements later
std::pair<int,int> p1;
p1.first = 3;
p1.second = 4;
std::cout << p1.first << " " << p1.second << std::endl;
//We can also create a pair using a constructor
std::pair<int,int> p2 = std::pair<int,int>(5, 6);
std::cout << p2.first << " " << p2.second << std::endl;
return 0;
}
Operators vergelijken
Parameters van deze operatoren zijn lhs en rhs
-
operator==test of beide elementen oplhsenrhspaar gelijk zijn. De retourwaarde istrueals beidelhs.first == rhs.firstANDlhs.second == rhs.second, andersfalse
std::pair<int, int> p1 = std::make_pair(1, 2);
std::pair<int, int> p2 = std::make_pair(2, 2);
if (p1 == p2)
std::cout << "equals";
else
std::cout << "not equal"//statement will show this, because they are not identical
operator!=test of elementen oplhsenrhspaar niet gelijk zijn. De retourwaarde istruealslhs.first != rhs.firstOFlhs.second != rhs.second, andersfalse.operator<test oflhs.first<rhs.first, retourneerttrue. Anders, alsrhs.first<lhs.firstfalseretourneert. Anders, alslhs.second<rhs.secondtrueretourneert, retourneert andersfalse.operator<=retourneert!(rhs<lhs)operator>geeftrhs<lhsoperator>=retourneert!(lhs<rhs)Een ander voorbeeld met containers van paren. Het gebruikt
operator<omdat het container moet sorteren.
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
#include <string>
int main()
{
std::vector<std::pair<int, std::string>> v = { {2, "baz"},
{2, "bar"},
{1, "foo"} };
std::sort(v.begin(), v.end());
for(const auto& p: v) {
std::cout << "(" << p.first << "," << p.second << ") ";
//output: (1,foo) (2,bar) (2,baz)
}
}