listコンストラクタ

提供:cppreference.com
移動: 案内, 検索


文法:

    #include <list>
    list();
    list( const list& c );
    explicit list( size_type 長さ, const T&= T() );
    list( input_iterator start, input_iterator end );
    ~list();

デフォルトのlistのコンストラクタは引数を取りません。新しいlistのインスタンスを作成します。

2つ目のコンストラクタはデフォルトのコピーコンストラクタです。与えられたlist cのコピーを行うときに使用されます。

3つ目のコンストラクタは指定された長さ分のスペースを作成します。もしも"値"が指定されると、それぞれのオブジェクトには、この"値"が割り当てられます。たとえば、次のサンプルコードは、42という数値のコピーを5個持つlistを作成します。

   list <int> l1( 5, 42 );

最後のコンストラクタは"start"と"end"の間の要素を含むように初期化されたlistを作成します。

サンプル:

   // 乱数の配列を作る
   cout << "オリジナルのlist: ";
   list<int> l;
   for( int i = 0; i < 20; i++ ) {
     int num = (int) rand() % 10;
     cout << num << " ";
     l.push_back( num );
   }
   cout << endl;
 
    // 5 & 7を削除
   list<int>::iterator iter1 = l.begin();
   while( iter1 != l.end() ) {
     list<int>::iterator thisone = iter1;
     ++iter1;
     if ( *thisone == 5 || *thisone == 7 ) {
		cout << "削除 " << *thisone << endl;
		l.erase( thisone );
	 }
   }
 
    // lの要素のうち、最初の偶数を見つける
   list<int>::iterator iter2 = l.begin();
   while( iter2 != l.end() && *iter2 % 2 != 0 ) {
     ++iter2;
   }
 
   // lの要素のうち、最後の偶数を見つける
   list<int>::iterator iter3 = l.end();
   do {
     --iter3;
   } while( iter3 != l.begin() && *iter3 % 2 != 0 );
 
   cout << "最初の偶数: " << *iter2 << ", 最後の偶数: " << *iter3 << endl;
 
   cout << "新しいlist: ";
   list<int> l2( iter2, iter3 );
   list<int>::iterator iter4 = l2.begin();
   while( iter4 != l2.end() ) {
     cout << *iter4 << " ";
	 ++iter4;
   }
   cout << endl;

これを実行すると、次のように出力されます:

  オリジナルのlist: 7 9 3 8 0 2 4 8 3 9 0 5 2 2 7 3 7 9 0 2 
  削除 7
   削除 5
   削除 7
   削除 7
   最初の偶数: 8, 最後の偶数: 2
   新しいlist: 8 0 2 4 8 3 9 0 2 2 3 9 0

すべてのコンストラクタは、最初のものを除いて 線形時間がかかります。最初のコンストラクタは 定数時間がかかります。

デフォルトのデストラクタはlist内のそれぞれのオブジェクトのデストラクタを呼び出します。線形時間かかります。

個人用ツール
名前空間
変種
操作
案内
ツールボックス
他の言語