C++ Numeric::iota() 函式



C++ 的std::numeric::iota() 函式用於填充一系列元素,使其具有順序遞增的值。它接受三個引數:起始迭代器、結束迭代器和起始值。它從提供的起始值開始,併為範圍中的每個後續元素遞增該值。

語法

以下是 std::numeric::iota() 函式的語法。

void iota (ForwardIterator first, ForwardIterator last, T val);

引數

  • first, last − 指示序列中初始和最終位置的迭代器。
  • val − 累加器的初始值。

返回值

異常

如果任何賦值或增量操作丟擲異常,則會丟擲異常。

資料競爭

訪問範圍 [first1,last1) 中的元素。

示例 1

在以下示例中,我們將考慮 iota() 函式的基本用法。

#include <iostream>
#include <numeric>
#include <array>
int main() {
   std::array < int, 4 > a;
   std::iota(a.begin(), a.end(), 1);
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

1 2 3 4 

示例 2

考慮以下示例,我們將用偶數填充陣列。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a(4);
   std::iota(a.begin(), a.end(), 0);
   for (int & x: a) {
      x *= 2;
   }
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

0 2 4 6

示例 3

讓我們看看以下示例,我們將用負值填充它。

#include <iostream>
#include <numeric>
#include <list>
int main() {
   std::list < int > a(4);
   std::iota(a.begin(), a.end(), -4);
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

輸出

以下是以上程式碼的輸出:

-4 -3 -2 -1
numeric.htm
廣告

© . All rights reserved.