场景
-
std::pair 可以打包最多两个值到一个类里,常用在需要返回两个值的函数里,因为可以不需要自己定义一个wrapper类,普通集合类肯定不能用,因为C++的集合只能存储泛型的(相同类型)对象. 如果要存储超过2个不同类型的对象, 可以使用 std::tuple, 它能存储最多10个不同对象类型. 是不是发现Java的集合可以存储任意类型强大很多,因为Java对象有共同的根类型,Object.
-
std::tuple是一个类模板,它能存储固定大小的(10个 vs2010)不同类型对象,它是std::pair的泛化类型.
-
std::tuple 也可以结合std::tie 来接收函数返回时 unpack 集合里的元素.
参考
std::tuple
std::tie
C/C++_操作符重载operator type()和operator()的区别
使用方法
#include "stdafx.h"
#include <tuple>
#include <set>
#include <iostream>
#include <map>
#include <assert.h>
#include <string>
#include <utility>
std::tuple<int, int> f()
{
int x = 6;
return std::make_tuple(x, 8);
}
void TestTuple()
{
int n = 1;
auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n,10);
n = 7;
std::cout << "The value of t is " << "("
<< std::get<0>(t) << ", " << std::get<1>(t) << ", "
<< std::get<2>(t) << ", " << std::get<3>(t) << ", "
<< std::get<4>(t) << ")\n";
int a, b;
std::tie(a, b) = f();
std::cout << a << " " << b << "\n";
std::set<std::string> set_of_str;
bool inserted;
std::tie(std::ignore, inserted) = set_of_str.insert("Test");
if (inserted)
{
std::cout << "Value was inserted sucessfully\n";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
TestTuple();
system("pause");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
输出:
The value of t is (10, Test, 3.14, 7, 1)
6 8
Value was inserted sucessfully