C++
std :: pair
수색…
쌍 만들기 및 요소 액세스
Pair를 사용하면 두 개의 객체를 하나의 객체로 처리 할 수 있습니다. 쌍은 템플릿 함수 std::make_pair 의 도움으로 쉽게 생성 할 수 있습니다.
또 다른 방법은 나중에 쌍을 만들고 요소 ( first 와 second )를 지정하는 것입니다.
#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;
}
연산자 비교
이 연산자의 매개 변수는 lhs 및 rhs
-
operator==lhs와rhs쌍의 두 요소가 동일한 지 여부를 테스트합니다.lhs.first == rhs.first와lhs.second == rhs.second양쪽 모두가true경우는true, 그렇지 않은 경우는false
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!=lhs및rhs쌍의 요소가 같지 않은지 테스트합니다.lhs.first != rhs.first또는lhs.second != rhs.second인 경우 반환 값은truelhs.second != rhs.second, 그렇지 않으면false반환합니다.operator<lhs.first<rhs.first인지 테스트하고true반환true. 그렇지 않으면,rhs.first<lhs.first가false반환하면. 그렇지 않은 경우,lhs.second<rhs.second가true돌려주는true는true, 그렇지 않은 경우는false리턴합니다.operator<=returns!(rhs<lhs)operator>는rhs<lhs반환합니다.operator>=반환합니다!(lhs<rhs)쌍 컨테이너가있는 또 다른 예입니다. 컨테이너를 정렬해야하기 때문에
operator<사용합니다.
#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)
}
}
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow