2011|08|
2013|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|05|06|07|08|09|10|11|12|
2016|01|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|

2019-02-21 STLについての自習 [長年日記]

push_back()によるクラスのリストが、実体を繋いでいるのか、コピーして繋いでいるのかの実験。

Newした以上DELETEが必要なのか、について調査中

/*
  g++ -g stl_test3.cpp -o stl_test3 -static-libstdc++ 
*/
 
#include <iostream>
#include <list>   // list 利用のため
using namespace std;
 
class PERSON
{
public:
  int age;
  int sex;
  int life; 
 
  PERSON(int _age, int _sex)
  {
	age = _age;
	sex = _sex;
	life = 1;
  }
 
  void func(void){
	age += 1;
  }
};
 
int main(){
 
  list<PERSON> person_list;
  
  PERSON *person1 = new PERSON(18, 0);
  PERSON *person2 = new PERSON(23, 1);
  PERSON *person3 = new PERSON(101, 1);
  PERSON *person4 = new PERSON(1, 1);
  PERSON *person5 = new PERSON(10, 10);
 
#if 0
  cout << "step1" << "\n";
  person3->life = -1; // 
  cout << person3->age << " " << person3->sex << " " << person3->life << "\n"; 
  cout << "\n";
#endif
 
  // どうやらpush_backはコピーするらしい
 
  person_list.push_back(*person1);
  person_list.push_back(*person2);
  person_list.push_back(*person3);
  person_list.push_back(*person4);
 
#if 1
  delete person1;
  delete person2;
  delete person3;
  delete person4;
  delete person5;
#endif
 
  cout << "step2" << "\n";
  list<PERSON>::iterator pos;
  for(pos = person_list.begin(); pos!=person_list.end(); ++pos){
	cout << pos->age << " " << pos->sex << " " << pos->life << "\n";
  }
  cout << "\n";
 
  person3->life = -1; // 
  cout << person3->age << " " << person3->sex << " " << person3->life << "\n"; 
  cout << "\n";
 
#if 1
  cout << "step3" << "\n";
  //list<PERSON>::iterator pos;
  for(pos = person_list.begin(); pos!=person_list.end(); ++pos){
	if (pos->age == 101){
	  pos->life = -1;
	  pos->func();
	}
  }
#endif
 
  cout << "step4" << "\n";
  // list<PERSON>::iterator pos;
  for(pos = person_list.begin(); pos!=person_list.end(); ++pos){
	cout << pos->age << " " << pos->sex << " " << pos->life << "\n";
  }
  cout << "\n";
 
 
 
#if 1 
 
  cout << "step5" << "\n";
  for ( pos = person_list.begin(); pos != person_list.end(); ){ //<-「it++」を削除
	if( pos->life == -1 ) {
      pos = person_list.erase( pos );
      continue;
	}
	pos++;  // ここで次のイテレートに
  }  
#endif
 
  cout << "step6" << "\n";
  //list<PERSON>::iterator pos;
  for(pos = person_list.begin(); pos!=person_list.end(); ++pos){
	cout << pos->age << " " << pos->sex << " " << pos->life << "\n";
  }
 
 
  return(0);
}
syntax2html