Reputation: 3
I have a 2D vector of string as
vector<vector<string>> database
it has following data
database[0] -> A C D (database[0][0] -> A , database[0][1] -> C and so on)
database[1] -> B C E F
database[2] -> A B C E F
database[3] -> B E
database[4] -> A C F
I am counting the occurrence of each string
(in this example each character A,B etc.) and saving it in a map
map_c
as
map<string,int> map_c ;
for(i=0 ; i<database.size() ; i++)
{
for(j=0 ; j<database.at(i).size() ; j++)
{
if(map_c.find(database.at(i).at(j)) != map_c.end())
{
map_c[database[i][j]]++;
}
else
{
map_c[database[i][j]] = 1;
}
}
}
And printing the count of each string using the code
for(map<string,int>::iterator it = map_c.begin() ; it != map_c.end() ; it++ )
{
cout << it->first << " -> " << it->second << endl;
}
Output ->
-> 1
A -> 3
B -> 3
C -> 4
D -> 1
E -> 3
F -> 3
Why NULL key has been created with a count 1 ?
Upvotes: 0
Views: 89
Reputation: 3
Sorry , finaly i got rid the problem. Problem was in the input file. At the end of the file , there was a space character at last line and i was thinking that my file has been over before it . That space was creating the problem. I am sorry for inconvenience and thank you so much for your replies and time .
Upvotes: 0
Reputation: 27365
The code you post should not generate an empty (or spaces) string. It is possible such a string comes with your initial data.
Either way, your code to fill the map can be made much much shorter:
map<string,int> map_c ;
for(const auto& line: database)
for(const auto& s: line)
++map_c[s];
Upvotes: 4
Reputation: 141574
Replace your if...else
with just ++map_c[database[i][j]];
. The default value for int
in a map is 0
.
The unexpected entry in your output is because your database
actually had that entry in it. If you are not sure why this entry is in your database, review the code that sets up your database (and/or post that code).
Upvotes: 3