andre andre - 3 months ago 16
C++ Question

vector subscript out of range when converting a char to int

I'm trying to access a vector in c++, but it throws subscript out of range

string s = "itwqbtcdprfsuprkrjkausiterybzncbmdvkgljxuekizvaivszowqtmrttiihervpncztuoljftlxybpgwnjb";
vector<int> result(s.size());
result.resize(s.size());
for (int i = 0; i < s.size(); i++)
{
int d = s[i];
result[d]++;
}

Answer

Not sure what you want with int d = s[i];, but d would be something like 'i' which is unrelated to result.size().

'i' is basically 105 in ASCII.

You probably want a map

const std::string s =
  "itwqbtcdprfsuprkrjkausiterybzncbmdvkgljxuekizvaivszowqtmrttiihervpncztuoljftlxybpgwnjb";
std::map<char, std::size_t> result;

for (char c : s)
{
   result[c]++;
}

for (const auto& p : result) {
    std::cout << "letter " << p.first << " appears " << p.second << "times\n"; 
}

If you want keep your vector, you may do something like:

const std::string s =
  "itwqbtcdprfsuprkrjkausiterybzncbmdvkgljxuekizvaivszowqtmrttiihervpncztuoljftlxybpgwnjb";
std::vector<std::size_t> result(26);

for (char c : s) {
    if ('a' <= c && c <= 'z') {
        result[c - 'a']++;
    }
}

for (std::size_t i = 0; i != result.size(); ++i) {
    std::cout << "letter " << char('a' + ) << " appears " << result[i] << "times\n"; 
}
Comments