C++ iota Algorithm: Usage Guide

In C++, the iota algorithm is an STL algorithm that is used to generate a series of sequentially increasing values. Its function signature is:

template <class ForwardIterator, class T>
void iota (ForwardIterator first, ForwardIterator last, T val);

In this, first and last are iterators representing the range to be filled with values, and val is the starting value. The iota function will fill the values in the given range incrementally starting from val.

Here is a basic example demonstrating how to use the iota algorithm in C++.

#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> vec(5); // 创建一个包含5个元素的vector
    std::iota(vec.begin(), vec.end(), 1); // 从1开始填充vector

    // 打印vector中的值
    for (int i : vec) {
        std::cout << i << " "; // 输出:1 2 3 4 5
    }
    
    return 0;
}

In the example above, we utilized the iota algorithm to populate a vector within the range of 1 to 5 and then printed out the results.

bannerAds