c++c++11iota

Using std::iota to fill an alphabet vector


In this code I'm filling the vector alpha with letters from 'a' to 'z':

std::vector<char> alpha(26);
std::iota(alpha.begin(), alpha.end(), 'a');

I'm assuming this will not work with all character encodings, can anyone confirm? Or deny?

And if the former is true, is there any solid alternative?


Solution

  • The behavior of std::iota is very simple:

    Fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value.

    This means your code will only work when the encoding represents the characters 'a', 'b' ... 'z' in increasing order. This is the case with ASCII encoding, so your code will work in that case. For any other encoding, where these characters are not increasing, or there are other characters interspersed between 'a' and 'z', this will not work.