在 std::p air : C++ STL 中使用 'std::make_pair”

Use of `std::make_pair` in std::pair : C++ STL

本文关键字:std make pair air C++ STL      更新时间:2023-10-16

我多次注意到,每当需要为(新)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;

我能想到的一些问题:

  1. 您并不总是准备好流对象。 std::cin是一个非常特殊的情况,std::make_pair是一个非常通用的函数。

  2. 谁说这对中的两种类型都支持operator>>

  3. 恒常正确性。您可能想要一对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);
}