we can directly input values to a pair, and modify them as we like.
For example:
std::pair<int,int> newp
std::cin>>newp.first>>newp.second
newp.first = -1
我可以想到一些问题:
你并不总是有一个流对象准备就绪。std::cin 是一个非常特殊的情况,而 std::make_pair 是一个非常通用的函数。
谁说这个 pair 中的两种类型都支持 operator>> 运算符呢?
常量正确性。你可能想要一个 const 的 pair。
让我们把这三件事结合起来,创建一个不能编译的示例:
#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)
{
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
可以解决这三个问题,并使代码更易读。请注意,您不必重复对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::make_pair
也有同样的问题。从根本上讲,这是语言和库之间的设计问题。你不能简单地编写一个由输入流按顺序初始化的异构对象声明列表。最接近的方法是定义带有流参数的构造函数,并为内置类型在流上进行转换操作。但是,使用这种风格仍然需要大量重复流名称。 - MSalters