在 std::p air : C++ STL 中使用 'std::make_pair”
Use of `std::make_pair` in std::pair : C++ STL
我多次注意到,每当需要为(新)std::pair
赋值时,都会使用std::make_pair
。但是我没有发现 make_pair
函数的任何用处,因为我们可以直接将值输入到一对中,并根据需要修改它们。例如:
std::pair<int,int> newp;
std::cin>>newp.first>>newp.second;
newp.first = -1;
那么这个功能到底有什么用呢?
std::make_pair
用于创建具有指定值的 std::pair
对象。
创建一个 std::p air 对象,从参数类型推断目标类型。
作为支持自动模板参数类型推断的模板函数,它允许您省略指定目标模板参数类型。
auto p1 = std::make_pair(1, 2); // p1 is std::pair<int, int> with value {1, 2}
有,它的优点叫做模板参数推导。它节省了一些打字,并允许您使用 auto
.类模板参数必须显式指定,函数不能。
但是在 C++17 中它变得多余,因为我们将有 模板参数推导 对于类模板
我们可以直接将值输入到一对中,并根据需要修改它们。 例如:
std::pair<int,int> newp; std::cin>>newp.first>>newp.second; newp.first = -1;
我能想到的一些问题:
-
您并不总是准备好流对象。
std::cin
是一个非常特殊的情况,std::make_pair
是一个非常通用的函数。 -
谁说这对中的两种类型都支持
operator>>
? -
恒常正确性。您可能想要一对
const
。
让我们把这三件事放在一起,创建一个非编译示例:
#include <utility>
#include <iostream>
struct Foo
{
int i;
};
struct Bar
{
double d;
};
void printPair(std::pair<Foo, Bar> const& pair)
{
std::cout << pair.first.i << " " << pair.second.d << "n";
}
void createAndPrintPairTwice(Foo const& foo, Bar const& bar)
{
// error 1: no std::cin, need to use foo and bar
// error 2: no operator>> for Foo or Bar
// error 3: cannot change pair values after initialisation
std::pair<Foo, Bar> const newp;
std::cin >> newp.first >> newp.second;
printPair(newp);
printPair(newp);
}
int main()
{
Foo foo;
foo.i = 1;
Bar bar;
bar.d = 1.5;
createAndPrintPairTwice(foo, bar);
}
std::make_pair
解决了所有三个问题,并使代码更易于阅读。请注意,您不必重复该对的模板参数:
void createAndPrintPairTwice(Foo const& foo, Bar const& bar)
{
std::pair<Foo, Bar> const pair = std::make_pair(foo, bar);
printPair(pair);
printPair(pair);
}
事实是,C++11 使std::make_pair
比以前有用得多,因为您现在还可以编写:
void createAndPrintPairTwice(Foo const& foo, Bar const& bar)
{
auto const pair = std::pair<Foo, Bar> { foo, bar };
printPair(pair);
printPair(pair);
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- 如何摆脱导入的 make 项目中的 Eclipse 索引器"Type std::... could not be resolved"错误
- Make zmqpp::socket::connect a std::future
- 为什么是 std::make_unique 而不是 std::unique_ptr::make?
- Travis ci make -std=c++14无法识别
- const decltype(*std::begin(container))& val dont make val const?
- make and std::logic_error