gpt4 book ai didi

C++ vector - push_back

转载 作者:行者123 更新时间:2023-11-30 00:59:11 31 4
gpt4 key购买 nike

在 C++ 入门书第 (3) 章中,有以下 for 循环将 vector 中的元素重置为零。

vector<int> ivec; //UPDATE: vector declaration
for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix)
ivec[ix] = 0;

for 循环真的为元素分配了 0 值,还是我们必须使用 push_back 函数?

那么,以下是否有效?

ivec[ix] = ix;

谢谢。

最佳答案

Is the for-loop really assigning 0 values to the elements? Or, we have to use the push_back finction?

ivec[ix] =0更新 vector 中现有元素的值,同时 push_back函数向 vector 添加新元素!

So, is the following valid?
ivec[ix] = ix;

完全有效IF ix < ivec.size() .

如果用iterator就更好了, 而不是索引。像这样,

int ix = 0;
for(vector<int>::iterator it = ivec.begin() ; it != ivec.end(); ++it)
{
*it = ix++; //or do whatever you want to do with "it" here!
}

使用iterator使用 STL 是惯用的。比索引更喜欢迭代器!

关于C++ vector - push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4850063/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com