Fix (block) the size of std :: vector

Is there a way to fix the size of the vector and still resize the content?

I tried to make const vector const std::vector<int> vec(10); but that prevents me from changing the values.

vec[3] = 3; gives compiler error: read-only location assignment.

I also tried using a constant reference to a non-constant vector

 std::vector<int> vec(10); const std::vector<int>& vecref(vec); 

which gives the same compiler error.

I want to be able to fix the size of the vector either in the declaration or after the initialization phase. I could use an old-fashioned array, but I want to be able to use vector algorithms.

I use g ++ if that matters.

+6
source share
4 answers

With C ++ 0x you can use std :: array <>, which is similar to the good old array, with the added benefit of being an STL container, which allows you to use many std :: algorithms.

Alternatively, you can try boost :: array.

Note that there is also std::tr1::array<> .


edit:

In fact, one of the cases when I was not involved was to grow a vector when reading configuration files, and then fix the size after that - DanS

Then why not this (illustrative):

 #include <vector> int main () { std::vector<int> foo; /* ... crunch upon foo ... */ // make a copy vector->vector: const std::vector<int> bar (foo); // make a copy any->vector const std::vector<int> frob (foo.begin(), foo.end()); } 

Alternatively, if you need reset () semantics, but you want to prevent resizing (), etc., you can write a container adapter:

 template <typename T, typename Allocator = allocator<T> > class resettable_array { public: // container ... typedef typename std::vector<T,Allocator>::iterator iterator; typedef typename std::vector<T,Allocator>::const_iterator const_iterator; ... iterator begin() { return vector_.begin() } const_iterator begin() const { return vector_.begin(); } ... void push_back (T const &v) { vector_.push_back (v); } ... // custom void reset () { ... } private: std::vector<T,Allocator> vector_; }; 

See also:

+6
source

Insert it into an object that provides only those operations that you want to allow.

Cheers and hth.,

+3
source

You can make const vector pointers and change the objects they point to. Not to say that this is the right answer, just to make it possible.

+1
source

Take a look at boost.array, it gives you a fixed-size array with vector semantics (except for anything that will resize the array).

+1
source

Source: https://habr.com/ru/post/892310/


All Articles