为什么我必须使用 std::make_pair?

Why do I have to use std::make_pair?

我已经用过typedef

typedef std::pair<int, int> coords;
typedef std::pair<float, coords> fcoords;

然后创建了一个这种数据类型的向量

std::vector<fcoords> openList;

所以当我尝试向向量添加一个元素时,为什么我必须使用 make_pair

int i = _start.first;
int j = _start.second;
openList.push_back(std::make_pair(0.0, std::make_pair(i, j)));

为什么我不能仅通过添加值来完成?

openList.push_back(0.0f, (i, j));

您可能会使用:

openList.push_back({0.0f, {i, j}});

可以,但需要使用正确的语法。例如

#include <iostream>
#include <utility>
#include <vector>

typedef std::pair<int, int> coords;
typedef std::pair<float, coords> fcoords;

int main() 
{
    std::vector<fcoords> v;

    v.push_back( { 1.0f, { 2, 3 } } );

    decltype( auto ) front = v.front();

    std::cout << front.first << ": " 
              << front.second.first << ", " 
              << front.second.second << '\n';

    return 0;
}

程序输出为

1: 2, 3

至于这个说法

openList.push_back(0.0f, (i, j));

然后用两个参数而不是一个参数调用成员函数push_back。第一个参数是浮点字面值 0.0f,第二个参数是带逗号运算符 (i, j) 的表达式,其结果是 j.

你可以这样做:

openList.emplace_back(0.0f, coords{i, j});