在C++中初始化成对的数组

Initializing an array of pair in C++

本文关键字:数组 初始化 C++      更新时间:2023-10-16

我想用以下方式初始化一个成对的数组:

pair<int, int> adjs[4] = {{current_node.first-1, current_node.second}, {current_node.first+1, current_node.second}, {current_node.first, current_node.second-1}, {current_node.first, current_node.second+1}};

然而,我的编译器Code::Blocks 12.1不断抛出错误:

brace-enclosed initializer used to initialize `std::pair<int, int>'|

我以前在一个在线编译器上使用过一次这种方法,它很有效。那么这是编译器的问题还是我代码中的语法问题呢?我不想逐一初始化4对。建议一种我可以消除这个错误的方法。

这个通用初始化语法是C++11的一个特性,您使用的编译器可能不支持C++11,但在线编译器支持。

你可以这样初始化你的数组:

pair<int, int> adjs[4] = {make_pair(current_node.first-1, current_node.second), ...};

一个活生生的例子:http://ideone.com/ggpGX9