简体   繁体   中英

Dynamic array in C++

I am new to C++ and programming. I would appreciate for some help with dynamic array sizing in C or C++.

ex :- I need to store values to array. ( vales can be changing )

set 1: 0,1,2,3

set 2 :- 0,1,2,3,4

set 3:- 0,1

set 4:- 0

So on I want them to store the value of set one in array process it and then store set 2 in same array process it and so on???

Please do reply back,

Thanks

The dynamic array in C++ is called std::vector<T> with T replaced with the type you want to store in it.

You'll have to put #include <vector> at the top of your program as well.

eg

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

Note to more experienced programmers : yes, a lot of things can be improved here (eg const references), but I'm afraid that would only confuse a beginning programmer.

You can use a std::vector :

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

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

Your question isn't completely clear, but it sounds as if you start with one set of data, perform some task on that set which produces another set, a task that uses the new set and creates yet another?

If that is the case, you'll probably want to learn about swap .

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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