C++ Vector Resize函数

Posted Harris-H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ Vector Resize函数相关的知识,希望对你有一定的参考价值。

C++ Vector Resize函数

Change size

Resizes the container so that it contains n elements.

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

void resize (size_type n, value_type val = value_type());

改变vector容器的大小。

改变容器的大小使他包含 n n n个元素。

  • 如果 n n n 小于当前容器大小,则内容减少到前 n n n个元素,移除后面的元素。
  • 如果 n n n 大于当前容器大小,则在后面插入一些元素至 n n n个大小,如果 v a l val val被定义则插入 v a l val val的复制,否则插入默认值 0 0 0
  • 如果 n n n大于当前容器的容量 ( c a p a c i t y ) (capacity) (capacity),则自动进行内容重新分配。

实例

// resizing vector
#include <iostream>
#include <vector>

int main ()

  std::vector<int> myvector;

  // set some initial content:
  for (int i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  std::cout << "myvector contains:";
  for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\\n';

  return 0;

结果

myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

以上是关于C++ Vector Resize函数的主要内容,如果未能解决你的问题,请参考以下文章

C++ vector的reserve和resize详解

C++:STL——vector的模拟实现

C++初识vector

C++中vector容器

vector的模拟实现(C++)

C++ STL中erase函数的用法 求助~~