Responsive Ad Area

Share This Post

test

Why does the map skip the first character?

I am trying to print the first occurence of each character in a string.

My code works, but for some reason it doesn’t record the first occurence of the very first character of my string.
I am using a map for this purpose(not the most ideal way, but I am trying to learn how to use them).

Code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    cin.ignore();
    while(t--){
        string s;
        getline(cin, s);
        map<char, int> m;
        for(int i=0; i<s.size();i++)
            if(!m[s[i]])
                m[s[i]]=i;
        for(auto i: m)
            cout<<i.first<<"-"<<i.second<<' ';
        cout<<endl;
        m.clear();
    }
return 0;
}

Input:

2
geeksforgeeks
geeks for geeks

My output:

e-1 f-5 g-8 k-3 o-6 r-7 s-4 
 -5 e-1 f-6 g-10 k-3 o-7 r-8 s-4 

Expected Output:

e-1 f-5 g-0 k-3 o-6 r-7 s-4 
 -5 e-1 f-6 g-0 k-3 o-7 r-8 s-4 


Why does the map skip the first character?
Why does the map skip the first character?
test
{$excerpt:n}

Share This Post

Leave a Reply

Your email address will not be Publishedd. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>