【发布时间】:2021-10-03 03:19:03
【问题描述】:
我正在编写一个读取文件并将内容放入地图的程序。该文件的内容类似于: 1 乙 3 C 3 2 ETC.. 基本上它只是字母表中的字母及其拼字游戏值。我将文件的内容放入地图中并且它可以工作,但我试图从之前给定值的字符串变量中调用地图。这是我现在的代码,你可以看到。
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <unordered_map>
int main() {
std::vector<std::string> scrabble;
{
std::ifstream scrabble_words("/srv/datasets/scrabble-hybrid");
for (std::string word; std::getline(scrabble_words, word);) {
scrabble.push_back(word);
}
}
int word_count = 0;
std::string word;
for (word; std::cin >> word;) {
std::for_each(word.begin(), word.end(), [](char& c) { c = ::toupper(c); });
if (std::find(scrabble.begin(), scrabble.end(), word) != scrabble.end()) {
word_count++;
}
}
std::unordered_map<std::string, int> points;
std::string letter;
std::ifstream in_file("/srv/datasets/scrabble-letter-values");
for (int worth; in_file >> letter >> worth;) {
points[letter] = worth;
}
std::cout << points[word[1]] << '\n';
我正在尝试通过之前设置的变量中的字符来访问地图的内容:
std::cout << points[word[1]] << '\n';
但是当我尝试这样调用它时,我会收到一页页我无法理解的错误消息,而且我不知道如何让它工作。我很确定这是因为 word[1] 的类型与字母的类型不同,但我不知道如何解决这个问题。
【问题讨论】:
-
word[1]是char,但您有std::unordered_map <***std::string***, int>。这意味着 unordered_map 的索引运算符将只接受std::string类型的操作数。如果你真的想使用键word[1]访问键值对,你必须先将其转换为字符串。 -
总是阅读第一个错误——你基本上可以忽略其余的。我总是使用
-fmax-errors=2代表gcc和-ferror-limit=2代表clang(如果你最多输入1,那么在第一个错误之后你会错过方便的note:)。 -
如果你准备一个minimal complete example,问题会更容易看到、理解和解决。
-
伙计,我完全看错了这个问题。
-
尝试将
word[1](即char)转换为std::string。请参阅this link 了解如何执行此操作的一些方法。
标签: c++