在 C++ 中初始化对数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26811196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:42:57  来源:igfitidea点击:

Initializing an array of pair in C++

c++compiler-errorsstl

提问by user1465557

I want to initialize an array of pair in the following way:

我想通过以下方式初始化一对数组:

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}};

However my compiler, Code::Blocks 12.1, keeps on throwing the error:

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

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

I used this method once before on an online compiler and it worked. So is it the problem with the compiler or some syntax issue in my code? I don't want to initialize 4 pair one by one. Suggest a way in which I can get rid of this error.

我之前在一个在线编译器上使用过这种方法并且它有效。那么是编译器的问题还是我的代码中的某些语法问题?我不想一一初始化 4 对。建议我可以摆脱这个错误的方法。

回答by mattnewport

This universal initialization syntax is a C++11 feature, likely the compiler you are using does not support C++11 but the online one did.

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

You can initialize your array like this instead:

您可以像这样初始化数组:

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

A live example: http://ideone.com/ggpGX9

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