C++中的动态数组

use*_*829 2 c++

我是C++和编程的新手.我很感激在C或C++中对动态数组大小的帮助.

例如: - 我需要将值存储到数组中.(价值可以改变)

设置1:0,1,2,3

第2集: - 0,1,2,3,4

第3组: - 0,1

第4集: - 0

所以我希望他们在数组处理中存储set one的值然后将set 2存储在同一个数组中,依此类推???

请回复,

谢谢

Sjo*_*erd 9

调用C++中的动态数组,将std::vector<T>T替换为要存储在其中的类型.

您还必须放在#include <vector>程序的顶部.

例如

#include <vector> // instruct the compiler to recognize std::vector

void your_function(std::vector<int> v)
{
  // Do whatever you want here
}

int main()
{
  std::vector<int> v; // a dynamic array of ints, empty for now

  v.push_back(0); // add 0 at the end (back side) of the array
  v.push_back(1); // add 1 at the end (back side) of the array
  v.push_back(2); // etc...
  v.push_back(3);
  your_function(v); // do something with v = {0, 1, 2, 3}

  v.clear();       // make v empty again
  v.push_back(10);
  v.push_back(11);
  your_function(v); // do something with v = {10, 11}
}
Run Code Online (Sandbox Code Playgroud)

请注意更有经验的程序员:是的,这里可以改进很多东西(例如const引用),但我担心这只会让初级程序员感到困惑.