sf::String 放入 std::map 键不起作用 - 该值未保存到地图中

sf::String put into std::map key doesn't work - the vaule is not saved into map

正如我在主题中所写 - 我尝试将 sf::String 放入地图第一个参数中,但它不起作用。这是代码:

void Flashcards::add(sf::String sf_string) {
std::string text = sf_string.toAnsiString();
std::pair<std::string,std::string> pairr = std::make_pair(text,"<Polish translation>");
std::cout << "Inserting: " << pairr.first << std::endl;
all_words.insert(pairr); //std::map<std::string, std::string> variable



void Flashcards::show() {
std::cout << "Flashcards:\n";
for (std::map<std::string, std::string>::iterator it = all_words.begin(); it != all_words.end(); it++)
{
    std::cout << "English word: " << it->first 
    << " " << "Polish word: " << it->second << std::endl;
}

控制台中的结果是:

Inserting: //a word//
Flashcards:
 Polish word: <Polish translation>

而不是需要:

Inserting: hello
Flashcards:
English word: //a word// Polish word: <Polish translation>

以下是我已经尝试过的变体:

1) 我切换了参数,所以它看起来像这样: std::make_pair("<Polish translation>",text); 并且它有效 - 硬编码键和值都显示在控制台中(但我不想硬编码,这是显而易见的) .

2) 请注意,这一行:std::cout << "Inserting: " << pairr.first << std::endl; 表明键值已正确转换为 std::string - 调用它会显示我们刚刚在键盘上键入的值。

3) 我试图将 sf::String 值直接发送到 std::make_pair() 方法,它的工作原理与将 std::string 放在那里完全相同。

有人能说说如何实现吗?

您作为参数提供给 add 方法的字符串显然以 \r(回车符 return)字符结尾,可能是因为您是从 Windows 文本文件使用 Unix/Linux 执行环境。如果您将程序的输出捕获到一个文件中并使用 hexdumper(例如 hd)查看它,您应该立即看到发生了什么。

肯定和你使用C++标准库没有关系。但是,您无需完成所有工作即可将条目插入 std::map。只需这样做:

all_words[key] = value;

只要 key 有正确的类型(或有自动转换),这将在一行中准确地完成您想要的,这行易于理解,而且可能效率更高。