fix(lock)std :: vector的大小 [英] fix (lock) size of std::vector

查看:162
本文介绍了fix(lock)std :: vector的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来修复一个向量的大小并仍然改变内容?

Is there a way of fixing the size of a vector and still changing the contents?

我已经尝试了一个const向量 const std :: vector< int>

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

vec [3] = 3;

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

我也尝试了一个非const向量的const引用

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.

我使用g ++如果这有什么区别。

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

推荐答案

使用C ++ 0x,可以使用std :: array<>,这是一个好的旧数组,是一个STL容器,因此允许许多std ::算法。

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.

或者,您可以尝试boost :: array。

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


  • a href =http://www.boost.org/doc/libs/1_46_1/doc/html/array.html =nofollow> boost :: array

  • std :: array li>
  • boost::array
  • std::array

注意,还有 std :: tr1 :: array<>

编辑:


实际上,我没有进入的情况之一是增长向量,同时读取配置文件,然后修正后的大小 - DanS

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());
}

或者,如果您需要reset()语义,但是要禁止resize )等,你可以写一个容器适配器:

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_;
};

另请参阅:

  • std::vector constructors

这篇关于fix(lock)std :: vector的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆