我是 C++ 和编程的新手。如果您能在 C 或 C++ 中动态调整数组大小方面提供一些帮助,我将不胜感激。
ex :- 我需要将值存储到数组中。 (值可以改变)
第 1 组:0,1,2,3
第 2 组:- 0,1,2,3,4
第 3 组:- 0,1
第 4 组:- 0
所以我希望他们将第一个集合的值存储在数组中处理它,然后将集合 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 引用),但恐怕这只会让新手程序员感到困惑。
关于c++ - C++中的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4506166/