[英]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.