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