矢量调整奇怪的行为

Kir*_*ran 2 c++ stl resize vector

我有以下代码.有趣的是,如果我取消注释向量上的resize(),它会输入10个数字,输入值为5.我在windows xp上使用eclipse和mingw和gcc.迭代器不应只用于5个元素吗?

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
//#include "stdio.h"
using namespace std;

template <typename T>
void print_coll(T t)
{
    typename T::iterator iter = t.begin();
    while (iter != t.end() )
    {
        cout << *iter << " ";
        ++iter;
    }
    cout << endl;
}

int main()
{
    int size;
    cin >> size;
    vector<int> numbers;
//    numbers.resize(size);

    for ( int i = 0 ; i < size; ++i ) {
        int r = (rand() % 10);
        numbers.push_back(r);
    }
    print_coll(numbers);

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 9

resize调整向量的大小,为新大小创建的每个项目插入默认值.你想要的reserve.