Home > OS >  Why unordered_map not showing correct index values of a vector?
Why unordered_map not showing correct index values of a vector?

Time:09-14

I have a string "codeforces" and now when i am storing characters of this string as key in an unordered map and index of occurrence of that character in a vector inside unordered map as value , then it is not showing correct indexes .

In this string "codeforces" character 'c' is occurring at index 1 and 8 , i would like to store character c as key in map and corresponding indexes of occurrences inside vector as value in unordered map . But when i am doing this it is not showing correct value . Can any body tell me why is this happening ?

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main(){ 
    string x = "codeforces";
    unordered_map<char,vector<int>> data;

    for(int i = 1;i <= x.size();i  ){
        data[x[i]].push_back(i);
    }

    for(auto it : data){
        if(it.first == 'c'){
            vector<int> out = it.second;
            for(int j = 0;j < out.size();j  ){
                cout<<out[j]<<" ";
            }
            cout<<endl;
        }
    }

    return 0;
}

Output should be like this (for character 'c') -> 1 8 .

But it is showing -> 7 .

CodePudding user response:

your for loop has a wrong range. You start at element 1 and because of <= only stop at the size of codeforces 1, which is out of bounds.

When iterating arrays the index starts at 0 and should end at size() - 1. This can be easily achieved by saying < size() as the less operator will result in false if the index is at size() - therefore size() - 1 is the last iteration step.


You have two options, either go from 1 to size() and access [i - 1]

for(int i = 1; i <= x.size(); i  ){
    data[x[i - 1]].push_back(i);
}

or go from 0 to size() - 1 and push_back(i 1)

for(int i = 0; i < x.size(); i  ){
    data[x[i]].push_back(i   1);
}

I recommend the latter, as it's the common way to iterate arrays.


read here why you should avoid writing using namespace std;.

  • Related