【问题标题】:Increasing the size of an array during runtime在运行时增加数组的大小
【发布时间】:2018-06-25 14:44:47
【问题描述】:

我想使用指针在 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 循环的大小。它可以根据执行条件和给定的输入而变化。我认为这不是正确的方法。有人可以建议一种方法吗?

【问题讨论】:

  • 如果你想要一个大小可以改变的数组,你想要一个std::vector
  • std::vector 为您执行此操作。如果您想自己实现这一点,则必须在需要更多内存时重新分配内存。
  • 那不是数组。那是指向指针的指针。如上所述,您应该更喜欢向量而不是原始数组或指针。

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


【解决方案1】:

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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    相关资源
    最近更新 更多