Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed size std::vector at runtime?

Performance is crucial in my application

I need something that works like std::experimental::dynarray, so an array which size is decided at runtime.

So I thought about using a wrapper class for std::vector, giving all its features, but without the possibility to call resize, reserve or push_back. In few words, all the methods to change its size (please remind me if I missed some of them).

So I started writing this class:

CCVector.hpp:

template <typename T>
class CCVector{
public:
    CCVector(size_t size);
    T &operator[](typename std::vector<T>::size_type idx);
private:
    std::vector<T> v;
};

CCVector.cpp:

template<typename T>
CCVector<T>::CCVector(size_t size) : v(size){}
template<typename T>
T& CCVector<T>::operator[](typename std::vector<T>::size_type idx){
    return  v[idx];
}

But I this point I thought I have to re-implement every method of std::vector that I need! For example begin, end, size etc, and I don't know how to implement all of them...Besides, this is really bad for maintenance: as soon as I need a new method from std::vector I need to re-implement it in CCVector.

All of this because I want fixed size arrays at runtime. How can I solve this without using the non-standard std::experimental::dynarray?

like image 611
justHelloWorld Avatar asked May 26 '26 07:05

justHelloWorld


1 Answers

Use private inheritance and then import the functions you want using the using declaration to introduce the names you want into your class.

template<class T>
class MyVector : private std::vector<T>
{
public:
    using std::vector<T>::end;
    // etc
};

(With private inheritance you don't get the issue with vector not having a virtual destructor which is the reason most people don't like inheriting from standard containers)

like image 146
Mike Vine Avatar answered May 30 '26 18:05

Mike Vine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!