-1

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 .

Study Planet
  • 153
  • 1
  • 7
  • 3
    No, output should be 7 since you skip the first 'c' that is at index 0. Your 1st loop should be ` for(int i = 0;i < x.size();i++)` , then you should get the correct result of 0 7. – Avi Berger Sep 14 '22 at 06:53
  • 1
    See [C++11: does unordered_map/set guarantees traversing order as insert order?](https://stackoverflow.com/questions/53389732/c11-does-unordered-map-set-guarantees-traversing-order-as-insert-order) – Jason Sep 14 '22 at 06:54
  • Indexing in C++ and most of programming is zero based (the first element of a sequence has index 0, not 1). – n. m. could be an AI Sep 14 '22 at 07:05
  • Thank you very much all of you , now i am getting correct answer . – Study Planet Sep 14 '22 at 07:12

1 Answers1

3

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;.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55