C++
std :: pair
Suche…
Ein Paar erstellen und auf die Elemente zugreifen
Paar ermöglicht es uns, zwei Objekte als ein Objekt zu behandeln. Mit Hilfe der Vorlagenfunktion std::make_pair können Paare leicht std::make_pair .
Alternativ können Sie ein Paar erstellen und dessen Elemente ( first und second Element) später zuweisen.
#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;
}
Operatoren vergleichen
Parameter dieser Operatoren sind lhs und rhs
-
operator==prüft, ob beide Elemente deslhsundrhsPaares gleich sind. Der Rückgabewert isttruewenn sowohllhs.first == rhs.firstlhs.second == rhs.second, andernfallsfalse
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!=prüft, ob Elemente auf dem Paarlhsundrhsnicht gleich sind. Der Rückgabewert isttruewenn entwederlhs.first != rhs.firstODERlhs.second != rhs.second, andernfallsfalse.operator<- Tests , wennlhs.first<rhs.firstkehrttrue. Andernfalls, wennrhs.first<lhs.firstfalsezurückgibt. Andernfalls, wennlhs.second<rhs.secondtruezurückgibt, andernfallsfalse.operator<=zurück!(rhs<lhs)operator>gibtrhs<lhsoperator>=zurück!(lhs<rhs)Ein anderes Beispiel mit Containern von Paaren. Es verwendet den
operator<da der Container sortiert werden muss.
#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)
}
}