在运行时增加数组的大小

时间:2018-06-25 14:44:48

标签: c++ c++11 pointers dynamic

我想使用指针在for循环中动态分配数组。随着for循环的进行,数组的大小应增加一,然后应添加一个新元素。通常的方法涉及使用new运算符,但是在声明时始终会分配固定的内存。有什么办法吗?

我尝试使用以下代码(为解释问题而简化):

sameCombsCount = 0;
int **matchedIndicesArray;    
for(int i = 0; i<1000; i++) //loop condition a variable
{
  sameCombsCount++;

  matchedIndicesArray = new int*[sameCombsCount]; // ??
  // Now add an element in the new block created...
}

问题是,我不知道执行期间for循环的大小。它可以根据执行条件和给定的输入而变化。我认为这不是正确的方法。有人可以建议这样做吗?

1 个答案:

答案 0 :(得分:0)

std::vector为您处理调整大小:

sameCombsCount = 0;
std::vecotr<int> matchedIndicesArray;    
for(int i = 0; i<1000; i++) //loop condition a variable
{
  sameCombsCount++;

#if 0
  matchedIndicesArray.resize(sameCombsCount);
  matchedIndicesArray.back() = someValue;
#else
  matchedIndicesArray.push_back(someValue);
#endif
}

第一个版本执行您想要的操作,并调整向量的大小,然后设置值。第二个版本只是将元素直接添加到数组的末尾,应该会稍微提高效率。

相关问题