我们可以直接将值输入到一对中,并根据需要对其进行修改。
例如:
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);
}