Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c++ - 为什么在C ++中对向量使用索引运算符被认为是不好的风格?(Why is it considered bad style to use the index operator on a vector in C++?)

I am working on a program that uses vectors.

(我正在使用矢量的程序。)

So the first thing I did was declare my vector.

(所以我要做的第一件事就是声明我的向量。)

std::vector<double> x;
x.reserve(10)

(BTW, is this also considered bad practice? Should I just type std::vector<double> x(10) ?)

((顺便说一句,这也被认为是不好的做法吗?我应该只输入std::vector<double> x(10)吗?))

Then I proceeded to assign values to the vector, and ask for its size.

(然后,我继续为向量分配值,并要求其大小。)

for (int i=0; i<10; i++)
{
    x[i]=7.1;
}
std::cout<<x.size()<<std::endl;

I didn't know it would return 0 , so after some searching I found out that I needed to use the push_back method instead of the index operator.

(我不知道它会返回0 ,所以经过一番搜索,我发现我需要使用push_back方法而不是索引运算符。)

for (int i=0; i<10; i++)
{
    x.push_back(7.1);
}
std::cout<<x.size()<<std::endl;

And now it returns 10 .

(现在返回10 。)

So what I want to know is why the index operator lets me access the value "stored" in vector x at a given index, but wont change its size.

(因此,我想知道的是为什么索引运算符允许我在给定索引下访问向量x中“存储”的值,但不会更改其大小。)

Also, why is this bad practice?

(另外,为什么这种不好的做法呢?)

  ask by Nerdrigo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do x.reserve(10) you only set the capacity to ten elements, but the size is still zero.

(当您执行x.reserve(10) ,仅将容量设置为十个元素,但大小仍为零。)

That means then you use the index operator in your loop you will go out of bounds (since the size is zero) and you will have undefined behavior .

(这意味着,然后在循环中使用index运算符将超出范围(因为大小为零),并且将具有未定义的行为 。)

If you want to set the size, then use either resize or simply tell it when constructing the vector:

(如果要设置大小,则在构造向量时可以使用resize或简单地告诉它:)

std::vector<double> x(10);

As for the capacity of the vector, when you set it (using eg reserve ) then it allocates the memory needed for (in your case) ten elements.

(至于向量的容量 ,当您设置它(使用例如reserve )时,它将为(在您的情况下)十个元素分配所需的内存。)

That means when you do push_back there will be no reallocations of the vector data.

(这意味着当您执行push_back ,将不会重新分配矢量数据。)

If you do not change the capacity, or add elements beyond the capacity, then each push_back may cause a reallocation of the vector data.

(如果您不更改容量或添加超出容量的元素,则每个push_back可能导致重新分配矢量数据。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...