Tuple
✏️ Pair
//类模板:
template<class T1,class T2> struct pairstd::pair<std::string, std::string> getAuthor() {
return std::make_pair("Zhang", "Liu");
}
void testPair(){
// 1、创建pair对象
std::pair<int, std::string> p1(10, "hello");
std::pair<int, std::string> p2(p1);
std::pair<int, std::string> p3;
p3 = p2;
typedef std::pair<std::string, std::string> Author;
Author author1("Tom", "Jack");
// 2、元素的操作
std::cout << "origin:" << p1.first << " " << p1.second << std::endl;
p1.first = 2;
p1.second = "world";
std::cout << "modify:" << p1.first << " " << p1.second << std::endl;
// 3、生成新的对象
p1 = std::make_pair(5, "Hello World!");
std::cout << "final:" << p1.first << " " << p1.second << std::endl;
// 4、对象间运算
std::cout << (p1 == p2) << std::endl;
std::cout << (p1 > p2) << std::endl;
// 两个pair对象间的小于运算,其定义遵循字典次序:
// 如 p1.first < p2.first 或者 !(p2.first < p1.first) && (p1.second < p2.second) 则返回true。
std::cout << (p1 < p2) << std::endl;
// 5、使用tie获取pair元素值
// 在某些清况函数会以pair对象作为返回值时,可以直接通过std::tie进行接收。
std::string name1,name2;
std::tie(name1, name2) = getAuthor();
std::cout << "Authors:" << name1 << " " << name2 << std::endl;
}✏️ Tuple/tie() --C++11
最后更新于