How to use the iota() function in C++

Key takeaways:

  • The iota() function assigns consecutive values starting from a given initial value to elements in a specified range.

  • It is part of the numeric header in C++.

  • The function modifies elements between the provided start and end iterators.

  • The starting value increments by 1 for each element in the range.

  • iota() does not return a value; it directly updates the sequence.

  • Useful for initializing arrays or containers with a sequence of numbers.

  • Requires iterators and works with any container supporting them.

The iota() function is available in the numeric header file in C++. iota() is used to assign successive values of value to every element in a specified range. The value gets incremented by 1 after assignment to an element.

Syntax of iota()

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

iota(first, last, val);

Parameters

The iota() method takes the following parameters:

  • first: Forward iterator for the initial position of the sequence to be written.

  • last: Forward iterator for the final position of the sequence to be written.

  • val: Initial value for the accumulator.

Forward iterators are iterators that can be used to access the sequence of elements in a range in the direction that goes from its beginning towards its end.

Return value

There is no return value.

Example of iota()

Let’s understand with the help of an example.

  • Array = num[16]

  • Range = [num,num+16) i.e from num[0] to num[15]

  • Value = 19

We have an array of size = 16, i.e., we can place the elements from index 0 to index 15. For the range, the iota() function includes the element pointed by first but excludes the element pointed by last.

The value in the accumulator is 19, which will get incremented by 1 after every assignment of value to the element until its range is met.

The result of the iota() function is:

  • 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Code implementation of iota()

Let’s look at the code snippet.

#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int num[16];
int val;
cin >> val;
iota(num,num+16,val);
cout<<"Elements are: ";
for(auto i:num)
{
cout<<' '<<i;
}
return 0;
}

Enter the input below

Explanation

  • Lines 1–2: We import the required header files.

  • Line 4: We make a main function.

  • Line 6: We declare an array of int type.

  • Line 7: We declare a variable of int type.

  • Line 8: We take the input of int type.

  • Line 9: We use the iota() function to assign the sequence of elements in the array.

  • Line 10: We display a message about the upcoming result.

  • Lines 11–14: We use the for loop to access the elements of the array and display them as a result.

In this way, we use the iota() function to generate the sequence of numbers in a specified range.

Using iota with custom data types

The iota() function in C++ is not limited to primitive data types; it can also be used with custom data types, provided the type supports addition and assignment operators. Here’s how:

  • Define a custom data type: Create a struct or class with members and overload the necessary operators (+ and =) for compatibility with iota().

#include <iostream>
#include <vector>
#include <numeric>
struct Point {
int x, y;
// Overload the increment operator
Point& operator++() {
++x;
++y;
return *this;
}
};
int main() {
std::vector<Point> points(5, {0, 0});
Point start = {1, 1};
std::iota(points.begin(), points.end(), start);
for (const auto& point : points) {
std::cout << "(" << point.x << ", " << point.y << ")\n";
}
return 0;
}

Explanation

  • Lines 1–3: We import the necessary header files for input/output (<iostream>), vector operations (<vector>), and numeric algorithms (<numeric>).

  • Lines 5–6: We define the Point struct with two integer members, x and y. The ++ operator is overloaded to increment both x and y by 1.

  • Line 16: The main function begins execution.

  • Line 17: A vector points of type Point is created with 5 elements, each initialized to {0, 0}.

  • Line 18: A Point object start is initialized with {1, 1} to serve as the starting value for the sequence.

  • Line 19: The iota() function fills the points vector with incrementing Point objects, starting from start.

  • Lines 21–23: A range-based for loop iterates over the points vector, printing each Point object in the format (x, y).

Time complexity

The time complexity of this program is O(n)O(n), where nn is the size of the vector. The std::iota function iterates through the vector once, assigning values to its elements sequentially.

Space complexity

The space complexity is O(1)O(1) for the operations performed by the program. The memory used by the vector (which is O(n)O(n)) is pre-allocated and not dynamically adjusted during the execution of std::iota or the loop. No additional space is used for computation.

Conclusion

The iota() function is a simple and efficient tool in C++ for generating sequential values within a specified range. It directly modifies the elements in a container, starting from an initial value and incrementing by 1 for each subsequent element. By understanding its parameters and usage, developers can easily initialize arrays or containers with sequential data, streamlining tasks such as testing and setup in their code. The function’s simplicity and utility make it a valuable addition to any programmer’s toolkit.

Unlock the world of programming from our C++ course: Learn C++ from Scratch which is perfect for beginners looking to build a solid foundation in coding!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Can `iota()` be used with characters?

Yes, std::iota can work with characters. It assigns sequential characters starting from the given initial value.


What happens if I use a negative starting value?

If you use a negative starting value, std::iota will generate sequentially increasing negative values.


Is `iota()` limited to vectors only?

No, std::iota is not limited to vectors. It can be used with any container that supports forward iterators.


Can I use `iota()` to fill a range in reverse order?

No, std::iota generates increasing values. To fill in reverse order, you need custom logic or modify the container afterward.


Can I use `iota()` to assign the same value to every element in the range?

No, std::iota assigns successive values. To assign the same value, use std::fill instead.


Free Resources