简体   繁体   中英

STD wrapper arround part of std::vector (or alternatives)

I currently use a std::vector to store some data (nb: the size is known at construction and don't changes afterwards: if you see a better structure than a vector, it's fine for me). Later in the program, I need to pass part of this data (the first N values) to an optimization function, that will modify it in place.

A simple solution would be to pass a reference to the whole vector, and an index of which part to use for optimization. But it would be nice if I could avoid telling the optimization function (and its sub-functions) which part to optimize, and just give them a vector/array/you_name_it containing only the values to be optimized.

So basically, I would like 2 "array" like objects (both constant size, but size only known at runtime) sharing the same memory.

For example, if std::vector had its members public, a simple solution would be

std::vector<int> original_vector={0,1,2,3,4,5,6,7,8}
std::vector<int> sub_vector(0);
sub_vector.data=original_vector->data; //point to the same data (nb : there is no public data member, just a data() getter, and as far as I know no setter)
sub_vector.length=3;
//sub_vector now appears to contain {0,1,2}
sub_vector[1]=42;
//oringinal_vector now contains {0,42,2,3,4,5,6,7,8}

Another solution would be to get the data pointer, and just pass a raw C style pointer + length to the optimization function. But it's not nice to have C pointers for arrays in C++. This could be a nice solution if there is a std container that can be initialized (without copy) by C pointer + length.

Any other ideas?

NB: I haven't written the optimizing code yet, so if it is easier, I can also put all the data to be optimized at the end instead of at the beginning.

NB: It would also be possible to create first the 2 "sub-arrays" (fixed data and data to be optimized) and then create the global array, provided there is a way without copying the data

EDIT: for now, I'm limited at C++17, because ROS2 don't support C+20 yet

Are you looking for std::span ?

std::vector<int> original_vector={0,1,2,3,4,5,6,7,8};
std::span<int> sub_vector(original_vector.begin(), 3);

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