简体   繁体   中英

Only allow a C++ vector to grow when resizing

Is there an alternative to resize() of an std::vector , which only allows the increase the size of the vector

std::vector v;
v.resize(10);
v.resize(5);

--> v.size() == 5 , but I like its length to stay at 10 and moreover I like its data not to be (potentially) deleted.

I could use

std::vector v;
v.resize(std::max(v.size(),10));
v.resize(std::max(v.size(),5));

This is a bit ugly. Is there a more elegant way?

This seems like a strange request. It would be interesting to know why you want this infinitely expanding vector. One solution (as suggested here ) would be to inherit from std::vector privately and implement your own resize, ie something like:

template <class T> // Can also forward the allocator if you want
class InfiniteResizeVector: private std::vector<T> 
// The private is very important, std::vector has no virtual destructor, so you 
// cannot allow someone to reference it polymorphically. 
{
public:
    using vector::push_back;
    using vector::operator[];
    ... // For all the functions you need
    void resize(size_t new_size) {
       vector::resize(std::max(size(),new_size));
    }
};

Usage would then just be v.resize(5); like you asked for. Make sure you read some of the other answers from the link above . This is a very unusual thing to do, unless this is something you will use all the time it is certainly not worth making your own independent type.

Fantastic Mr Fox offers to solve this problem through inheritance and rewriting, but it's possible to solve this problem through combinationcomposition, but it's probably a little more troublesome, and here's my example.

template<typename T>
class OnlyGrowVector {
public:
    using size_type = typename std::vector<T>::size_type;

    void push_back(T&& t)
    {
        m_vector.push_back(std::forward<T>(t));
    }

    T& operator[](size_type idx)
    {
        return m_vector[idx];
    }
... // for what you need
    void resize(size_type size)
    {
        m_vector.resize(std::max(m_vector.size(), size));
    }

private:
    std::vector<T> m_vector;
};

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