Skip to content

Instantly share code, notes, and snippets.

@Nyarll
Last active July 2, 2020 00:41
Show Gist options
  • Save Nyarll/d0268a2214a1524d44721c87cd15084d to your computer and use it in GitHub Desktop.
Save Nyarll/d0268a2214a1524d44721c87cd15084d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ivector;
//ivector.reserve(1000);
ivector.push_back(0);
ivector.push_back(1);
ivector.resize(1000);
ivector.resize(100);
// resize だと、sizeは100になるがcapacityは1000のまま
// reserve をしても、size も capacity も変化しない
ivector.push_back(1);
// この時点でのivector
// size : 101
// capacity : 1000
std::cout << "vector size : " << ivector.size() << std::endl;
std::cout << "vector capa : " << ivector.capacity() << std::endl;
// <swap技法> C++以前
// 実はstd::vectorは、clearを呼べばOKのように思われるが、clearはsize(要素数)を0にするだけ
// clearではsizeは0になるが、capacity(内部で確保されているメモリ)は解放されないままになっているので厄介なときがある
// どうすればcapacityを解放できるのか?それは、vectorのデストラクタを呼ぶしかない
// そこで用いられるのが、swap技法と呼ばれる手法です
{
std::vector<int> backup = ivector;
// <クリアしてみる>
ivector.clear();
std::cout << "clear - - - - - - - - - - - - - - - - - " << std::endl;
std::cout << "vector size : " << ivector.size() << std::endl;
std::cout << "vector capa : " << ivector.capacity() << std::endl;
ivector = backup;
// これだとcapacity, sizeは100にすることができるが、中身も入れ替わってしまうので元のデータが消えてしまう
// std::vector<int> temp(100);
// ivector.swap(temp);
// 名前のないオブジェクトのコンストラクタに、切り詰めたいvector(今回はivector)を渡す
// ivectorのcapacityをsize分まで切り捨てることになる
std::vector<int>().swap(ivector);
// swapを使って一時オブジェクトと交換した際にデストラクタが呼ばれるらしい
// これで、ivectorは size 101, capacity 101となる
}
// C++11以降は、shrink_to_fitを使うことが適切
std::cout << "swap- - - - - - - - - - - - - - - - - - " << std::endl;
std::cout << "vector size : " << ivector.size() << std::endl;
std::cout << "vector capa : " << ivector.capacity() << std::endl;
std::cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment