C++ vector - push_back

标签 c++ vector push-back

在 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/

相关文章:

c++ - vector push_back 似乎在推送不正确的值

c++ - 将字符串推送到私有(private)成员 vector

c++ - vector push_back 在类对象中不起作用

c++ - 派生类中重载最终函数

java - OpenGL 正确附加纹理

r - 如何从R中的向量中洗牌?

arrays - 在 GLSL 着色器中使用小型查找表

c++ - 类范围和私有(private)成员?

c++ - 创建一个使用模板创建类或子类对象的函数

c++ - 为什么我不能返回一个 vector<vector<int>> (Process returned -1073741819 (0xC0000005))