[英]How do I construct a subrange of vector by reference?
I am currently utilizing the range constructor of std::vector
to create another vector of a given subrange.我目前正在利用
std::vector
的范围构造函数来创建给定子范围的另一个向量。
std::vector<int> myVect { 1, 2, 3, 4 };
std::vector<int> subrangeVector(myVect.begin(), myVect.begin() + 2);
However, this results in the ranged values of myVect being copied and taking up additional memory.但是,这会导致 myVect 的范围值被复制并占用额外的内存。 This is something that is undesirable when working withing limited memory and/or with very large element types.
当使用有限的内存和/或非常大的元素类型时,这是不可取的。
How do I construct a subrange of another vector by reference?如何通过引用构建另一个向量的子范围?
A simplified explanation of my objective is as follows:我的目标的简化解释如下:
void fun(std::vector<int> & v) { v.at(0) = 1; }
int main()
{
std::vector<int> myVect { 1, 2, 3, 4 };
std::size_t upperLimit = 5;
std::vector<int> subrangeVector = subrangeView(myVect, upperLimit);
fun(subrangeVector); // so myVect.at(0) == 1
return 0;
}
This would be implemented in many different functions that utilize std::vector
as a parameter.这将在使用
std::vector
作为参数的许多不同函数中实现。 I do not want to pass iterators as discussed here .我不想传递这里讨论的迭代器。 Assume that I have no control over the function
fun
.假设我无法控制函数
fun
。
A C++ vector is a type which "owns" its memory - it cannot be a "reference type" into another vector's data. C++ 向量是一种“拥有”其内存的类型——它不能是另一个向量数据的“引用类型”。
Instead, you will likely find a span useful: A span is a class representing contiguous data in memory - just like a vector;相反,您可能会发现跨度很有用:跨度是表示内存中连续数据的类——就像向量一样; but - it is a "reference type", and it is not owning - just what you wanted to have.
但是 - 它是一种“引用类型”,它不拥有 - 正是您想要的。 It behaves like a vector wrt iteration,
operator[]
, and so on.它的行为类似于向量 wrt 迭代、
operator[]
等。
In your case, you would write:在你的情况下,你会写:
std::vector<int> myVect { 1, 2, 3, 4 };
auto subrange { std::span{myVect}.subspan(0, 2); }
and then use subrange just as you were planning to with the vector.然后按照您计划使用矢量的方式使用子范围。
PS: This is C++20 code, since C++17 doesn't have spans yet; PS:这是 C++20 代码,因为 C++17 还没有跨度; if you're using earlier C++ versions, use
gsl::span
from the Guidelines Support Library (eg from here ).如果您使用的是较早的 C++ 版本,请使用指南支持库中的
gsl::span
(例如来自此处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.