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)
看來你很困惑reserve()和resize()。 –
改變:dist [k] =(-1.0 + k * 2.0 /(base-1.0));'對此:'dist.at(k)=(-1.0 + k * 2.0/);'。一旦你這樣做,問題應該是顯而易見的。 – PaulMcKenzie