C++ 为向量分配内存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4427738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:23:13  来源:igfitidea点击:

Allocate memory for a vector

c++vector

提问by Prasanth Madhavan

Can someone give me an example of how to allocate memory for a vector? A couple of lines is all I need. I have a vector that takes in 20-30 elements.. but when i try to cout it and compile it i only get the first couple of entries..

有人能给我一个如何为向量分配内存的例子吗?我只需要几行。我有一个包含 20-30 个元素的向量。

回答by Frédéric Hamidi

An std::vectormanages its own memory. You can use the reserve()and resize()methods to have it allocate enough memory to fit a given amount of items:

一个标准::矢量管理它自己的内存。您可以使用Reserve()resize()方法让它分配足够的内存来容纳给定数量的项目:

std::vector<int> vec1;
vec1.reserve(30);  // Allocate space for 30 items, but vec1 is still empty.

std::vector<int> vec2;
vec2.resize(30);  // Allocate space for 30 items, and vec2 now contains 30 items.

回答by Simon Hughes

Take a look at thisYou use list.reserve(n);

看看这个你用list.reserve(n);

Vector takes care of its memory, and you shouldn't really need to use reserve() at all. Its only really a performance improvement if you already know how large the vector list needs to be.

Vector 负责处理它的内存,您根本不需要使用 Reserve()。如果您已经知道向量列表需要多大,它只是真正的性能改进。

For example:

例如:

std::vector<int> v;
v.reserve(110); // Not required, but improves initial loading performance

// Fill it with data
for(int n=0;n < 100; n++)
    v.push_back(n);

// Display the data
std::vector<int>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
    cout << *it;