C++ 向量庫 - vector() 函式



描述

C++ 填充建構函式 std::vector::vector() 構造一個大小為n的容器,並將值val(如果提供) 分配給容器的每個元素。

宣告

以下是來自 std::vector 標頭檔案的填充建構函式 std::vector::vector() 的宣告。

C++98

explicit vector (size_type n, const value_type& val = value_type(), 
   const allocator_type& alloc = allocator_type());

C++11

vector (size_type n, const value_type& val,
   const allocator_type& alloc = allocator_type());
      explicit vector (size_type n);

引數

  • n − 容器的大小。

  • val − 要分配給容器每個元素的值。

返回值

建構函式永不返回值。

異常

此成員函式永不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例顯示了填充建構函式 std::vector::vector() 的用法。

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v(5, 200);

   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

200
200
200
200
200
vector.htm
廣告