C++11stlintermediate
std::iota (C++11 Addition)
C++11 · Modern Revolution · Compiler flag: -std=c++11
Explanation
Fills a range with sequentially increasing values starting from a given value, provided by the `<numeric>` header.
Real-World Scenario
Generate sequential ticket numbers or indices for a seating chart.
Quick Snippet
snippet.cpp
#include <numeric>
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 1); // {1, 2, 3, ..., 10}Full Example
iota.cpp
// CodeNebula - C++11 Example: std::iota Fill with Incrementing Values
// Compile: g++ -std=c++11 -Wall -Wextra -o example iota.cpp
// std::iota fills a range with sequentially increasing values, starting
// from a given initial value. Each subsequent element is generated by
// applying prefix ++ to the previous value. Defined in <numeric>.
#include <iostream>
#include <vector>
#include <numeric>
#include <list>
#include <array>
int main() {
// Fill a vector with 1, 2, 3, ..., 10
std::vector<int> nums(10);
std::iota(nums.begin(), nums.end(), 1);
std::cout << "1 to 10: ";
for (const auto& n : nums) std::cout << n << " ";
std::cout << std::endl;
// Fill starting from a different value
std::vector<int> from_five(6);
std::iota(from_five.begin(), from_five.end(), 5);
std::cout << "Starting at 5: ";
for (const auto& n : from_five) std::cout << n << " ";
std::cout << std::endl;
// Fill with negative starting value
std::vector<int> neg(7);
std::iota(neg.begin(), neg.end(), -3);
std::cout << "Starting at -3: ";
for (const auto& n : neg) std::cout << n << " ";
std::cout << std::endl;
// Works with std::array
std::array<int, 5> arr;
std::iota(arr.begin(), arr.end(), 100);
std::cout << "Array from 100: ";
for (const auto& n : arr) std::cout << n << " ";
std::cout << std::endl;
// Works with std::list
std::list<int> lst(4);
std::iota(lst.begin(), lst.end(), 10);
std::cout << "List from 10: ";
for (const auto& n : lst) std::cout << n << " ";
std::cout << std::endl;
// Works with characters
std::vector<char> letters(26);
std::iota(letters.begin(), letters.end(), 'a');
std::cout << "Alphabet: ";
for (const auto& c : letters) std::cout << c;
std::cout << std::endl;
// Practical: generate indices for an algorithm
std::vector<int> indices(8);
std::iota(indices.begin(), indices.end(), 0);
std::cout << "Indices: ";
for (const auto& i : indices) std::cout << i << " ";
std::cout << std::endl;
// Works with floating point
std::vector<double> doubles(5);
std::iota(doubles.begin(), doubles.end(), 1.5);
std::cout << "Doubles from 1.5: ";
for (const auto& d : doubles) std::cout << d << " ";
std::cout << std::endl;
return 0;
}
// Expected output:
// 1 to 10: 1 2 3 4 5 6 7 8 9 10
// Starting at 5: 5 6 7 8 9 10
// Starting at -3: -3 -2 -1 0 1 2 3
// Array from 100: 100 101 102 103 104
// List from 10: 10 11 12 13
// Alphabet: abcdefghijklmnopqrstuvwxyz
// Indices: 0 1 2 3 4 5 6 7
// Doubles from 1.5: 1.5 2.5 3.5 4.5 5.5
Run command
g++ -std=c++11 -Wall -Wextra -o example iota.cpp