sf::字符串放入 std::map 键不起作用 - vaule 没有保存到地图中

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

本文关键字:vaule 保存 地图 不起作用 字符串 std map sf      更新时间:2023-10-16

正如我在主题中所写的那样-我试图将sf::String放入map第一个参数中,但它不起作用。下面是代码:

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(回车)字符结束,可能是因为您正在使用Unix/Linux执行环境从Windows文本文件中读取它。如果您将程序的输出捕获到一个文件中,并使用hexdumper(如hd)查看它,您应该立即看到发生了什么。

这当然与你使用c++标准库无关。但是,在std::map中插入一个条目并不需要做所有这些工作。只需这样做:

all_words[key] = value;

只要key具有正确的类型(或者存在自动转换),就可以在一行中精确地完成您想要的内容-易于理解的行,并且可能更有效。