Back to TILs

C++ iota

Date: 2018-08-15Last modified: 2024-11-02
template <typename T>
void print( const string &label, T &container )
{
  string separator;
  cout << label << " = [";
  for( const auto &item : container ) {
    cout << separator << item;
    separator = ", ";
  }
  cout << "]" << endl;
}
  array<int, 4>   ints1;   // 💩 array preenchido com valores presentes na memoria (lixo)
  array<int, 26>  ints2{}; // array preenchido com zero
  array<char, 5>  chars;   // 💩
  array<float, 5> floats{};

  print( "ints1", ints1 );
  print( "ints2", ints2 );

  iota( ints1.begin(), ints1.end(), 10 );
  print( "ints1", ints1 );

  iota( ints2.rbegin(), ints2.rend(), 10 );
  print( "ints2", ints2 );

  iota( chars.begin(), chars.end(), 'a' );
  print( "chars", chars );

  iota( floats.begin(), floats.end(), 50.3 );
  print( "floats", floats );

Output

ints1 = [0, 0, 0, 0]
ints2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ints1 = [10, 11, 12, 13]
ints2 = [35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
chars = [a, b, c, d, e]
floats = [50.3, 51.3, 52.3, 53.3, 54.3]