我注意到很多次,无论什么时候需要为(新)分配值std::pair,都会std::make_pair被使用.但是我没有找到任何make_pair函数的使用,因为我们可以直接将值输入到一对,并根据需要修改它们.例如:
std::pair<int,int> newp;
std::cin>>newp.first>>newp.second;
newp.first = -1;
Run Code Online (Sandbox Code Playgroud)
那究竟是什么功能的使用?
std::make_pair用于创建std::pair具有指定值的对象.
创建一个std :: pair对象,从参数类型中推导出目标类型.
作为支持自动模板参数类型推导的模板函数,它允许您省略指定目标模板参数类型.例如,
auto p1 = std::make_pair(1, 2); // p1 is std::pair<int, int> with value {1, 2}
Run Code Online (Sandbox Code Playgroud)
我们可以直接将值输入到pair中,并根据需要修改它们。例如:
Run Code Online (Sandbox Code Playgroud)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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
事实是,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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2505 次 |
| 最近记录: |