I want to get a range of elements from a std::vector<MyClass>
and store them as const
-ref, because I only want to read but not modify them.
#include <iostream>
#include <vector>
// A "large" user class
class MyClass
{
public:
int data;
MyClass(int val) : data(val) {}
};
int main()
{
// Initialize vector to MyClass objects
std::vector<MyClass> myClass{1, 2, 3, 4, 5, 6, 7, 8};
// Get const reference to element with index 0
const auto &el = myClass[0];
// Get const references to a range of elements
const unsigned int start = 1, end = 4;
// const auto &elRange = ???
return 0;
}
How can I achieve something like this in C++17 or lower?
std::span
if you can upgrade to C++20, or simply store the indices in the new vector. – Beastlyconst_iterator
s:const auto elRangeBegin = myClass.cbegin() + 1; const auto elRangeEnd = myClass.cbegin() + 4;
– Gymnasiumstd::span<const MyClass>
? – Banff