2016-08-02 116 views
3

我有以下脚本,在一个特定的基础创建了所有可能的点:矢量大小添加

int main(){ 

    int base; 
    cout << "Enter Base: "; 
    cin >> base; 

    int dimension; 
    cout << "Enter Dimension: "; 
    cin >> dimension; 

    //This creates all possible numbers 
    vector<double> dist; 
    dist.reserve(base); 
    for(int k=0; k<base; k++){ 
    dist[k] = (-1.0+k*2.0/(base-1.0)); 
    } 

    vector< vector<double> > points; 
    int perms = 1; 
    for(int i=0; i<dimension; i++){ 
    perms *= base; 
    } // base^dimension 
    points.reserve(perms); 

    vector<double> stand; 
    stand.reserve(dimension); 

    // Defined later 
    getPermutations(dist, base, stand, dimension, 0, points); 

    for(int i=0; i<points.size(); i++){ //DOESN'T DO ANYTHING BECAUSE SIZE IS 0 
    cout << '('; 
    for(int j=0; j<points[i].size(); j++){ 
     cout << points[i][j] << ','; 
    } 
    cout << ')' << endl; 
    } 

    return 0; 
} 

它不会做任何事情,因为当我使用的push_back大小功能不仅增加()函数而不是索引。我必须使用索引,因为排列的功能如下:

void getPermutations(vector<double>& arr, int size, 
        vector<double>& data,int dimension, 
        int index, vector< vector<double> >& combs){ 
    int i; 
    //stop recursion condition 
    if(index == dimension){ 
    combs.push_back(data); 
    } 
    else{ 
    for(i = 0; i < size; i++){ 
     data.at(index) = arr.at(i); 
     getPermutations(arr, size,data, 
         dimension,index+1, combs); 
    } 
    } 
} 

我不明白为什么矢量大小是零和错误不断弹出说:

terminate called after throwing an instance of 'std::out_of_range' 
    what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0) 
+3

看来你很困惑reserve()和resize()。 –

+0

改变:dist [k] =(-1.0 + k * 2.0 /(base-1.0));'对此:'dist.at(k)=(-1.0 + k * 2.0/);'。一旦你这样做,问题应该是显而易见的。 – PaulMcKenzie

回答

8

std::vector::reserve功能不做你认为它的事情。它不会改变大小,只是容量(为矢量分配的内存量)。

这意味着当您创建例如在dist载体,并呼吁reserve后直接您有一个循环,并做

dist[k] = (-1.0+k*2.0/(base-1.0)); 

你实际上是索引出界并具有不确定的行为。

解决的方法是实际设置大小。无论是通过std::vector::resize,或创建载体时,简单地设置大小:

std::vector<double> dist(base); // Creates vector with a specific size 

你有你所有的矢量相同的问题,所有这些都需要相应地改变。