4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

std::vectorをswapで解放したあとにresize()すると消した要素が復活する

Posted at

初投稿でこんな頭の悪い記事を書くのも恥ずかしいのですが…
何も考えずに脊髄だけでプログラム書いてたら出くわした現象です。

hoge.cpp
std::vector<int> test = {1, 2};
std::vector<int>().swap(test); //時折解説サイトで見かける初期化法

test.resize(2); //こんなことする人もいないとは思う
test.push_back(3);
test.push_back(4);
test.push_back(5);

for(int i = 0; i < test.size(); i++) {
 std::cout << "test[" << i << " = " << test[i] << std::endl;
 /* 出力結果:
  test[0] = 1
  test[1] = 2
  test[2] = 3
  test[3] = 4
  test[4] = 5
 */
}

そもそもやろうとしてたことが頭悪かったので、特に解決策なんかは探してません。
shrink_to_fit()とか使えば出来そうな気はします。

環境依存かもしれないのでコンパイラの情報も載せます。

icpc version 15.0.3 (gcc version 4.4.6 compatibility)

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?