矢量调整大小奇怪的行为
我有以下代码。有趣的是,如果我取消对向量上的 resize() 的注释,它会为输入值 5 打印 10 个数字。我在 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);
}
I have the following code. The interesting part is if I uncomment the resize() on vector, it is priting 10 numbers for an input value of 5. I am using eclipse with mingw and gcc on windows xp. Shouldn't the iterator go only for 5 elements?
#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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
resize
调整向量的大小,为需要为新大小创建的每个项目插入默认值。您想要保留
。resize
resizes the vector, inserting default values for each of the items it needs to create for the new size. You wantreserve
.这会将
size
0 添加到向量中。这会将
size
随机值添加到向量中。您可能想要
保留
而不是调整大小
。reserve
不会更改向量的“可见”大小,它只会更改向量使用的存储的内部大小,而resize
会更改“可见”大小。This adds
size
0's to the vector.And this adds
size
random values to the vector.Likely you wanted
reserve
notresize
.reserve
does not change the "visible" size of the vector it only changes the internal size of the storage used by the vector,resize
however changes the "visible" size.