У меня небольшая проблема с кодом ниже.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
std::map<std::string, int> m; //Dictionary map
int main() {
std::ifstream dictionaryFile("dictionary.txt");
std::string str;
int probability = -1;
//Read dictionary.txt and assign to map
while(std::getline(dictionaryFile, str)) {
if(str.find("#!comment:") == std::string::npos) { //Not a comment
m.insert(std::pair<std::string, int>(str, probability));
}
else {
probability++;
}
}
dictionaryFile.close();
//Iterate and print through map -- THIS WORKS
std::map<std::string, int>::iterator pos;
for(pos = m.begin(); pos != m.end(); ++pos) {
std::cout << "Key: " << pos->first << std::endl;
std::cout << "Value: " << pos->second << "\n" << std::endl;
}
//Is "very" in the map? -- THIS DOES NOT WORK
std::cout << m.find("very")->second << std::endl;
if(m.find("very") != m.end()) {
std::cout << "found it" << std::endl;
} else {
std::cout << "did not find it" << std::endl;
}
}
Я читаю в файле "dictionary.txt" и вставляю каждое слово в карту.1 или 2 - это значение, связанное с этим ключом, в зависимости от вероятности слова.
Я могу перебирать карту и печатать ее элементы из цикла for, как показано.Но я не могу получить доступ к каждому элементу индивидуально с помощью m.find (), m.count () или оператора [].Каждый из них выглядит так, как будто карта пуста.
У меня неправильный синтаксис?Обнаружил ли я ошибку в std :: map?Буду признателен за любую помощь!
Вот dictionary.txt , если хотите.