我试图从一个无序的映射中接收值
std::string
作为键,其中一些字符串只包含一个字符。我所有的输入都来自
std::stringstream
从中获取每个值并将其转换为char,然后使用
std::string result {1, character};
documentation
和
this answer
.
为什么会发生这种情况,我该如何解决?
#include <iostream>
#include <sstream>
#include <unordered_map>
int main()
{
const std::unordered_map<std::string, int> map = { {"H", 1}, {"BX", 2} };
std::stringstream temp {"Hello world!"};
char character = static_cast<char>(temp.get()); // character is 'H'
std::string result {1, character}; // string contains "\x01H"
std::cout << result << " has length " << result.size() << std::endl; // H has length 2
std::cout << map.at(result) << std::endl; // unordered_map::at: key not found
}