c++ - vector 大小不会随着变量的添加而增加

标签 c++ vector size stdvector

我有以下脚本可以在特定基础上创建所有可能的点:

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

我不明白为什么 vector 大小为零并且不断弹出错误:

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)

最佳答案

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

这意味着当您创建例如dist vector 并在调用 reserve 后直接执行循环并执行

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

您实际上是在越界索引并且有未定义的行为。

解决方案是实际设置大小。通过std::vector::resize ,或者在创建 vector 时简单地设置大小:

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

你所有的 vector 都有同样的问题,所有的 vector 都需要相应地改变。

关于c++ - vector 大小不会随着变量的添加而增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38726302/

相关文章:

c++ - 难以理解 C++ 依赖类型,以及当前实例化的内容

c++ - 说C++标准中语法选项的表示中没有隐含顺序是正确的吗?

c++ - vector 和频率搜索

uiview - 在自定义 View 上定位图像,需要澄清

C++ 从文件 I/O 解析数据

C++ - 需要帮助理解删除功能

c++ - 指针可以放在堆内存上吗(C++)?

c++ - stringstream 没有按预期工作

c++ - 一个变量中的最大指针数

label - 获取带有自动换行的 SWT 标签的大小