调用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引用),但我担心这只会让初级程序员感到困惑.