C++ 为什么我必须使用std::make_pair?
我已经用过typedef了C++ 为什么我必须使用std::make_pair?,c++,c++11,path-finding,C++,C++11,Path Finding,我已经用过typedef了 typedef std::pair<int, int> coords; typedef std::pair<float, coords> fcoords; 为什么我不能仅仅通过在中添加值来实现呢 openList.push_back(0.0f, (i, j)); 您可以使用: openList.push_back({0.0f, {i, j}}); 可以,但需要使用正确的语法。比如说 #include <iostream> #i
typedef std::pair<int, int> coords;
typedef std::pair<float, coords> fcoords;
为什么我不能仅仅通过在中添加值来实现呢
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;
}
至于这句话,
openList.push_back(0.0f, (i, j));
然后用两个参数而不是一个参数调用成员函数push_back
。第一个参数是float literal0.0f
,第二个参数是带有逗号运算符(i,j)
的表达式,其结果是j
您可以执行以下操作:
openList.emplace_back(0.0f, coords{i, j});
在你看来,它就像一个结构,但当你在表达式中使用逗号时,它实际上是一个类似“+”或“/”的运算符。“括号中的东西”是一个表达式。逗号运算符返回逗号后的值。因此,对于编译器来说,表达式是“push_back(0,(j)),它简化为“push_back(0,j)”。为什么?我不知道有50年历史的语言中的设计,但答案中的解决方法很好。我建议您不要使用pair,而是使用Structure,因为元素可以有有有意义的名称。要访问
第二个coords
你必须写openList[1]。第二个。第二个很难读。它可以写成openList[1].coords.y
,看起来很棒。谢谢,这很有效,而且是如此简单的修复。最糟糕的是,我在脑海里就知道了:汉克斯,这很有效,而且是这么简单的修复。最糟糕的是,我早就知道这一点:D
#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));
openList.emplace_back(0.0f, coords{i, j});