2012-12-08 57 views
2

我想创建一个外部矢量固定(总是包含相同矢量)的vector<vector<int>>,但可以更改内部矢量。例如:只制作矢量中的外部矢量<vector<int>>修复

int n = 2; //decided at runtime 
assert(n>0); 
vector<vector<int>> outer(n); //outer vector contains n empty vectors 

outer.push_back(vector<int>()); //modifying outer vector - this should be error 

auto outer_it = outer.begin(); 
(*outer_it).push_back(3); //modifying inner vector. should work (which it does). 

我想这样做只是const vector<vector<int>>,但是这使得即使是内部向量const

是我创建自己的自定义FixedVectors类的唯一选择,还是有更好的方法来做到这一点?

+0

你需要n在运行时才能被决定吗?或者它可以是一个编译时间常量? –

+0

你有没有考虑过使用const数组? – ATaylor

+1

为什么不使用数组来创建常量数组大小?我没有看到为什么你需要使它具体成为一个矢量的原因。 –

回答

1

裹外载体导入刚刚提供的,开始,结束和operator []的一类。让这个类只有一个构造函数正在发挥其能力。

这很可能是最好的方法。

+0

对不起,没有看到你建议包装自己 –

2

definition

载体是表示可以在 大小改变阵列序列的容器。就像数组一样,向量使用连续的存储位置来表示它们的元素,这意味着它们的元素也可以通过在其元素的常规指针上使用偏移量来访问 ,就像在数组中一样高效地使用 。但与阵列不同的是,它们的大小可以动态地更改为 ,其容量将自动由 容器处理。

,如果你不希望有一个数据结构,改变尺寸,载体可能不适合的外层最好的选择,如何有关使用矢量的阵列。这样数组的大小是固定的,不能修改,但仍然可以在运行时声明大小。

vector<int> *outer; 
int VectSize; 
cout >> "size of vector array?" 
cin >> VectSize; 
outer = new vector<int>[VectSize]; //array created with fixed size 
outer.push_back() //not happening 
1
const vector<unique_ptr<vector<int>>> outer = something(n); 

对于东西,你可以写一个函数,就像这样:

vector<unique_ptr<vector<int>>> something(int n) 
{ 
    vector<unique_ptr<vector<int>>> v(n); 
    for (auto & p : v) 
     p.reset(new vector<int>); 
    return v; 
}