简体   繁体   中英

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);
?

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.

The exact same code int *p = &a[1]; works if a is a vector too.

But it's really not recommended. it's even worse than with the array because a vector can reallocate, and your pointer will be invalidated.

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