简体   繁体   English

STD wrapper arround std::vector 的一部分(或替代品)

[英]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).我目前使用 std::vector 来存储一些数据(注意:大小在构造时已知,之后不会改变:如果你看到比向量更好的结构,那对我来说很好)。 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.在程序的后面,我需要将部分数据(前 N 个值)传递给优化函数,该函数将就地修改它。

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.但是,如果我可以避免告诉优化函数(及其子函数)要优化哪一部分,并且只给它们一个只包含要优化的值的向量/数组/you_name_it,那就太好了。

So basically, I would like 2 "array" like objects (both constant size, but size only known at runtime) sharing the same memory.所以基本上,我想要 2 个像对象一样的“数组”(都是恒定大小,但大小仅在运行时已知)共享相同的内存。

For example, if std::vector had its members public, a simple solution would be例如,如果 std::vector 使其成员公开,一个简单的解决方案是

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.另一种解决方案是获取数据指针,然后将原始 C 样式指针 + 长度传递给优化函数。 But it's not nice to have C pointers for arrays in C++.但是在 C++ 中为数组使用 C 指针并不好。 This could be a nice solution if there is a std container that can be initialized (without copy) by C pointer + length.如果有一个可以通过 C 指针 + 长度初始化(无需复制)的 std 容器,这可能是一个很好的解决方案。

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注意:也可以先创建 2 个“子数组”(固定数据和要优化的数据),然后创建全局数组,前提是有一种不复制数据的方法

EDIT: for now, I'm limited at C++17, because ROS2 don't support C+20 yet编辑:目前,我仅限于 C++17,因为 ROS2 还不支持 C+20

Are you looking for std::span ?您在寻找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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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