开发者

fix (lock) size of std::vector

Is there a way开发者_如何学Python of fixing the size of a vector and still changing the contents?

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

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

I have also tried with a const reference to a non-const 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 vector size either on declaration or after an initialisation stage. I could use an old fashioned array, but I want to be able to use the vector algorithms.

I'm using g++ if that makes any difference.


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

Alternatively, you may want to try boost::array.

  • boost::array
  • std::array

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


edit:

Actually, one of the cases that I hadn't gone into was to grow the vector while reading configuration files and then fix the size after that - DanS

Then, why not this (illustrational):

#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 want to forbid resize() et al, you could 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:

  • std::vector constructors


Embed it in an object that provides only the operations that you want to allow.

Cheers & hth.,


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


Take a look at boost.array, it gives you a fixed size array with vector semantics (with the exception of anything that would change the size of the array).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜