C++ 演算法庫 - fill_n() 函式



描述

C++ 函式 std::algorithm::fill_n() 將值賦給由first.

指向的序列的前 n 個元素。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::fill_n() 函式的宣告。

template <class OutputIterator, class Size, class T>
void fill_n(OutputIterator first, Size n, const T& val);

C++98

  • 引數

  • first − 指向初始位置的輸出迭代器。

  • n − 要填充的元素數量。

val − 用於填充範圍的值。

返回值

異常

如果元素賦值或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性。

示例

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

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

   fill_n(v.begin() + 2, 3, 4);

   cout << "Vector contains following elements" << endl;

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}

即時演示

Vector contains following elements
1
1
4
4
4
讓我們編譯並執行上述程式,這將產生以下結果:
列印頁面
廣告