从std :: string获取第一个char

abr*_*hab 1 c++ string char

我需要std::string用最少量的代码获得第一个字符.

如果可以从STL获得一行代码中的第一个字符,那将是很棒的std::map<std::string, std::string> map_of_strings.以下代码是否正确:

map_of_strings["type"][0]
Run Code Online (Sandbox Code Playgroud)

编辑 目前,我正在尝试使用这段代码.这段代码是否正确?

if ( !map_of_strings["type"].empty() )
    ptr->set_type_nomutex( map_of_strings["type"][0] );
Run Code Online (Sandbox Code Playgroud)

set_type函数的原型是:

void set_type_nomutex(const char type);
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 5

如果你把一个非空字符串放进去,那应该有用map_of_strings["type"].否则,您将获得一个空字符串,并且访问其内容可能会导致崩溃.

如果您无法确定字符串是否存在,则可以测试:

std::string const & type = map["type"];
if (!type.empty()) {
    // do something with type[0]
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想避免向地图添加空字符串:

std::map<std::string,std::string>::const_iterator found = map.find("type");
if (found != map.end()) {
    std::string const & type = found->second;
    if (!type.empty()) {
        // do something with type[0]
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,at如果字符串为空,您可以使用范围检查并抛出异常:

char type = map["type"].at(0);
Run Code Online (Sandbox Code Playgroud)

或者在C++ 11中,地图也有类似的地方at,您可以使用它来避免插入空字符串:

char type = map.at("type").at(0);
Run Code Online (Sandbox Code Playgroud)