andre
andre

Reputation: 155

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]++;
    }

Upvotes: 0

Views: 69

Answers (2)

Jarod42
Jarod42

Reputation: 217970

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"; 
}

Upvotes: 2

Spencer
Spencer

Reputation: 2214

Simply put, s.size () is the wrong value to resize result with. I would try something like

 vector<int> result(CHAR_MAX, 0);

and remove the call to resize, which is not so much redundant as it is actively pernicious.

Upvotes: -1

Related Questions