-1

I'm studying for a exam next week and I've come across a question in my book that I can't get to work. Says that suppose set<char> s; is declared now write a loop to insert all 26 letters into s.

What I've got is

for(int i = 0; i < 26; i++)
{
     s.insert('A') + i;
}

Something similar to this would work for an array I believe, but not for this template class. I know I don't have to insert each letter I just don't know how I could run through the alphabet.

chanse.s
  • 13
  • 4

3 Answers3

1

For portability, don't assume that uppercase letters have contiguous encodings; there are character encodings where your code would not work correctly. Instead:

const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 26; ++i)
    s.insert(letters[i]);
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

Make this:

 s.insert('A') + i;

as

 s.insert('A' + i);

or

 s.insert(65 + i);   // 'A' value in ASCII table is 65

or as answered by user31264

for (char c = 'A'; c <= 'Z'; ++c)
    s.insert(c);

you can test by printing all element using:

for (auto e:s)
    cout << e;
Shadi
  • 1,701
  • 2
  • 14
  • 27
0
for (char c = 'A'; c <= 'Z'; ++c)
    s.insert(c);
user31264
  • 6,557
  • 3
  • 26
  • 40