assign

来自cppreference.com
跳转到: 导航, 搜索

Syntax:

語法:

    #include <vector>
    void assign( size_type num, const T& val );
    void assign( input_iterator start, input_iterator end );

The assign() function either gives the current vector the values from start to end, or gives it num copies of val.

vector 使用 assign() 方法來給元素賦值,有兩種方式:

  1. 從一個已知 vector 使用 startend 來給當前 vector 賦值
  2. 使用 numval 拷貝來給當前 vector 賦值。


This function will destroy the previous contents of the vector.

這個方法會破壞 vecotr 先前的內容。

For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:

例如:下面的代碼使用 assign() 把 10 個整數 42 賦給 vecotr:

   vector<int> v;
   v.assign( 10, 42 );
   for( vector<int>::size_type i = 0; i < v.size(); i++ ) {
     cout << v[i] << " ";
   }
   cout << endl;

The above code displays the following output:

上述代碼的運行結果如下:

  42 42 42 42 42 42 42 42 42 42

The next example shows how assign() can be used to copy one vector to another:

下面這個例子展示怎樣使用 assign() 來複制一個 vector 到另一個 vector:

   vector<int> v1;
   for( int i = 0; i < 10; i++ ) {
     v1.push_back( i );
   }
 
   vector<int> v2;
   v2.assign( v1.begin(), v1.end() );
 
   for( vector<int>::size_type i = 0; i < v2.size(); i++ ) {
     cout << v2[i] << " ";
   }
   cout << endl;

When run, the above code displays the following output:

運行上述代碼,顯示結果如下:

  0 1 2 3 4 5 6 7 8 9

Related Topics: insert, push_back, [] operator

相關主題: insert push_back[] operator

个人工具
名字空间
操作
导航
工具箱
其他语言