繁体   English   中英

C ++中的动态数组

[英]Dynamic array in C++

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

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

设置1:0,1,2,3

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

第3组: - 0,1

第4集: - 0

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

请回复,

谢谢

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}
}

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

你可以使用std::vector

向量容器实现为动态数组; 就像常规数组一样,向量容器将其元素存储在连续的存储位置,这意味着它们的元素不仅可以使用迭代器访问,还可以使用常规指向元素的偏移量来访问。

好像你想要一个std :: vector <int>

您的问题并不完全清楚,但听起来好像您从一组数据开始,在该组上执行一些生成另一组的任务,一个使用新组的任务并创建另一组?

如果是这种情况,您可能想要了解swap

例如

int main(void)
{
    std::vector<int> inputs, outputs;
    // push_back something into inputs

    // perform some task 1 on inputs which fills in outputs
    inputs.swap(outputs); // now the outputs of task 1 have become the inputs of task 2
    outputs.clear();

    // perform some task 2 on inputs which fills in outputs
    inputs.swap(outputs); // now the outputs of task 2 have become the inputs of task 3
    outputs.clear();

    // perform some task 3 and so on

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM