C++
std :: जोड़ी
खोज…
एक जोड़ी बनाना और तत्वों तक पहुंच बनाना
जोड़ी हमें दो वस्तुओं को एक वस्तु के रूप में मानने की अनुमति देती है। टेम्प्लेट फ़ंक्शन 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जोड़ी बराबर हैं। वापसी मूल्यtrueअगर दोनोंlhs.first == rhs.firstऔरlhs.second == rhs.second, अन्यथा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जोड़ी पर कोई तत्व समान नहीं हैं। रिटर्न वैल्यूtrueअगर या तोlhs.first != rhs.firstयाlhs.second != rhs.second, अन्यथाfalselhs.second != rhs.second।operator<परीक्षण अगरlhs.first<rhs.first,true। अन्यथा, अगरrhs.first<lhs.firstfalse। अन्यथा, अगरlhs.second<rhs.secondtrue, अन्यथा,falseदेताfalse।operator<=रिटर्न!(rhs<lhs)operator>रिटर्नrhs<lhsoperator>=रिटर्न!(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)
}
}