Вы пытаетесь сохранить один и тот же константный символ * для каждого слова, потому что вы никогда не создаете новую память для слова, извлеченного из файла. Если вы распечатаете указатель, возвращаемый из temp_str.c_str()
, он будет одинаковым для каждого вызова в вашем первом цикле. Во втором цикле вы печатаете один и тот же символ * для каждой записи на вашей карте (обратите внимание, что только 1 б / к карта не допускает дублирование), для которой задана пустая строка либо в 1-м цикле, либо между Ваш цикл.
Вот пример кода, который демонстрирует проблему и решение.
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
int main (int argc, char **argv)
{
ifstream file("test.txt");
map<const char *, int> dictionary;
map<string, int> strDictionary;
string temp_str;
int counter = 0;
while (!file.eof())
{
file >> temp_str;
cout << "PARSED: " << temp_str << "\n";
cout << "INSERTING: " << (unsigned long) temp_str.c_str() << "\n";
dictionary.insert(make_pair(temp_str.c_str(), counter));
strDictionary.insert(make_pair(temp_str, counter));
counter++;
}
cout << "Dictionary Size: " << dictionary.size() << "\n";
cout << "Str Dictionary Size: " << strDictionary.size() << "\n";
for (map<const char*, int>::const_iterator iter = dictionary.begin();
iter != dictionary.end();
++iter)
{
cout << "CHAR * DICTINARY: " << iter->first << " -> " << iter->second << "\n";
}
for (map<string, int>::const_iterator iter = strDictionary.begin();
iter != strDictionary.end();
++iter)
{
cout << "STR DICTIONARY: " << iter->first << " -> " << iter->second << "\n";
}
return 1;
}