C ++ 11中的简单向量初始化返回奇怪的错误 [英] Simple vector initialization in C++11 returns weird error
问题描述
编译这段代码:
#include <vector>
long long sumOfMedians(int seed, int mul, int add, int N, int K)
{
std::vector<int> nos{N+2,0};
for(int i=0; i<N; i++)
{
if(i == 0)
nos[i] = seed;
else
nos[i] = (nos[i-1]*mul + add)%65536;
}
}
int main()
{
sumOfMedians(3,1,1,10,3);
return 0;
}
导致错误
*** Error in `./a.out': free(): invalid next size (fast): 0x00000000006e8010 ***
[2] 31743 abort (core dumped) ./a.out
虽然略微更改了向量初始化行(上一代码中的第5行)到(新代码中的5,6行)
While slightly changing the vector initialization line (line 5 in previous code) to (line 5,6 in new code)
#include <vector>
long long sumOfMedians(int seed, int mul, int add, int N, int K)
{
std::vector<int> nos;
nos.resize(N+2,0);
for(int i=0; i<N; i++)
{
if(i == 0)
nos[i] = seed;
else
nos[i] = (nos[i-1]*mul + add)%65536;
}
}
int main()
{
sumOfMedians(3,1,1,10,3);
return 0;
}
使其成功编译。
g ++参数:-std = c ++ 11
g++ parameter: -std=c++11
推荐答案
对于 vector
,括号初始化将矢量内容初始化为初始化程序列表的内容,因此
For vector
, brace-initialisation initialises the vector contents to the contents of the initialiser list, so
std::vector<int> nos{N+2,0};
将其初始化为2号,元素 N + 2
和 0
。这使用构造函数,该构造函数采用类型为 std :: initializer_list
的单个参数。
initialises it to a size of 2, with elements N+2
and 0
. This uses the constructor that takes a single parameter of type std::initializer_list
.
将花括号更改为括号会导致而是使用由两个参数组成的构造函数,该构造函数为所有元素指定大小和初始值。这就是您想要的;虽然您可以省去第二个参数,因为默认情况下元素是零初始化的。
Changing the braces to parentheses causes it to instead use the two-argument constructor that specifies the size and initial value for all elements. That's what you want here; although you could leave out the second argument since elements are zero-initialised by default.
这篇关于C ++ 11中的简单向量初始化返回奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!