Open In App

iota() in C++

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, iota() is a library function used to fill a range of elements with increasing values starting from the given initial value. It assigns the starting value to the first element and then increments it once for the next element and so on.

Let’s take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(5);

    // Assign increasing values starting from 1
    iota(v.begin(), v.end(), 1);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 3 4 5 

This article covers the syntax, usage, and common examples of iota() function in C++:

Syntax of iota()

The iota() function is defined inside the <numeric> header file.

iota(first, last, val);

Parameters:

  • first: Iterator to the first element of the range.
  • last: Iterator to the element just after the last element of the range.
  • val: Starting value.

Return Value:

  • This function does not return any value.

Note: iota() function only works for those STL containers that support random access using index numbers such as vector, dequeu, etc.

Examples of iota()

iota() can be used with any range with data types that have a well-defined increment operation (++). The below examples demonstrate the use of iota() with different containers and its behaviour in different conditions.

Initializing Array Elements using iota()

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    char arr[5];
  	int n = sizeof(arr)/sizeof(arr[0]);

    // Assigning arr elements with sequentially 
    // increasing values starting from 'a'
    iota(arr, arr + n, 'a');

    for (auto i : arr)
        cout << i << " ";
    return 0;
}

Output
a b c d e 

Using iota with Custom Data Types

C++
#include <bits/stdc++.h>
using namespace std;

struct C {
    int a;
  
  	// Defining ++ for struct C
    C& operator++() {
        ++a;
        return *this;
    }
};

int main() {
    vector<C> v(5);

    // Fill the vector starting from Counter{1}
    iota(v.begin(), v.end(), C{1});

    for (auto i: v) {
        cout << i.a << " ";
    }
    return 0;
}

Output
1 2 3 4 5 

Time Complexity: O(n), where n is the number of elements in the given range.
Auxiliary Space: O(1)

Explanation: For iota() to work, the ++ operator must be defined for data type used in the range. So, for custom data type, we need to manually implement the ++ operator as done in struct C.



Next Article
Article Tags :
Practice Tags :

Similar Reads