ベクターでのsize()の使用法は使い果たされています

ベクターでのsize()の使用法は使い果たされています

先赞后看,养成好习惯。有帮助的话,点波关注!我会坚持更新,感谢谢您的支持!

参考
std::vector::resize

要件: デバッグプログラムでベクトルを 0 に設定する問題があり、最終的にリサイズが不正に使用されていることが判明したので記録します。


状況の簡単な説明

1. ベクターを初期化してから、resize() を使用してすべての要素に値を割り当てたい

vector<int> test = {0,1,2,3,4};
test.resize(10,0);
// 打印结果
for(const auto &value: test) std::cout << value << ","; 
std::cout << std::endl;

通常、出力結果は 10 個の 0 であると考えられますが、実際にはそうではありません。0,1,2,3,4,0,0,0,0,0,

2. Resize() 関数の説明

2.1 関数プロトタイプ(C++11)

void resize (size_type n);
void resize (size_type n, const value_type& val);

2.2 公式説明

Resizes the container so that it contains n elements.

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

2.3 使用説明書

  • n個の要素が含まれるようにコンテナのサイズを変更します
  • n が現在のコンテナ サイズより小さい場合、コンテンツは最初の n 要素と删除それ以降の要素に縮小されます (そしてそれらは解放されます)。
  • n が現在のコンテナ サイズより大きい場合、コンテンツは最後に必要な要素数だけ拡張され、插入n のサイズに達します。val が指定されている場合、新しい要素は val のコピーになるように初期化され、そうでない場合は 0 に初期化されます。
  • n が現在のコンテナ容量よりも大きい場合、割り当てられたストレージは自動的に再割り当てされます。

この関数は、插入或删除コンテナの実際の内容を要素ごとに変更することに注意してください。

2.4 実践例

公式サンプルをお借りします。

// resizing vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some initial content:
  for (int i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  std::cout << "myvector contains:";
  for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

結果:
myvector には以下が含まれます: 1 2 3 4 5 100 100 100 0 0 0 0

説明:

  • 1から9までの9個の要素を初期化します。
  • 最初の操作size(5)は最後の4つの要素を削除し、この時点では 1 2 3 4 5 を残します。
  • 2 番目の操作、resize(8,100) は最後に 3 つの要素を挿入します。その 3 つの要素の値は 100 です。
  • 3 番目の操作、resize(12) では、最後に 12-8=4 要素が再度挿入されます。要素の初期値が提供されていないため、デフォルト値の 0 が使用されます。

2.5 拡張

プロジェクトの実際の要件は、プログラムの開始時にメンバー変数 Vector のすべての要素を 0 に設定し、最後に fillstd::fill() 関数を使用することです。この関数はclear()値をクリアしますが、メモリは解放しません。

std::fill(input_data_.begin(), input_data_.end(), 0);  // 填充
input_data_.clear(); // 清空后,遍历打印则看不到结果

おすすめ

転載: blog.csdn.net/weixin_36354875/article/details/126274661