Search code examples
c++stdvector

C++: Can I define vector within another vector?


In C/C++ pure array, you can define an array within another array, for example:

int a[5];
int *p = &a[1];

So that if you change p[0] it would affect a[1] so on and so forth. Is there similar mechanism in vector?

vector<int> a(5, 0);
?

Solution

  • Your first example

    int a[5];
    int *p = &a[1];
    

    does not define an array within another array, it only creates a pointer to an element inside the exisiting array. For standard containers like std::vector the same can be achieved by using iterators:

    vector<int> a(5, 0);           // a = [0, 0, 0, 0, 0]
    auto iterator = a.begin() + 1; // "points" to a[1]
    *iterator = 2;                 // a = [0, 2, 0, 0, 0]
    

    Iterators are widely used in the standard library and the go-to-solution to provide access to (sub-)ranges of containers.


    If you can use C++20 or later you might want to look at std::span instead.