2012-04-23 506 views
1

我需要使用最少量的代码获取std::string的第一个字符。从std :: string获取第一个字符

如果能够从STL std::map<std::string, std::string> map_of_strings中获得一行代码中的第一个字符,那将是非常棒的。在下面的代码正确:

map_of_strings["type"][0] 

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

if (!map_of_strings["type"].empty()) 
    ptr->set_type_nomutex(map_of_strings["type"][0]); 

set_type函数的原型是:

void set_type_nomutex(const char type); 
+10

“不起作用”不是问题描述。 – 2012-04-23 19:03:57

+0

你是什么意思“不能正常工作”?发生了什么?你期望会发生什么? – 2012-04-23 19:03:59

+0

你确定原型是正确的吗?如果你使用'type'作为map的键,你应该得到一个编译错误。 – 2012-04-23 19:04:20

回答

2

这不是从你的问题你的问题是什么十分清楚,但事情可能map_settings["type"][0]出错是因为返回的字符串可能为空,导致在您执行[0]时出现未定义的行为。如果没有第一个字符,你必须决定你想要做什么。这是一种可能性,可以在单一行中起作用。

ptr->set_type_nomutex(map_settings["type"].empty() ? '\0' : map_settings["type"][0]); 

它获取第一个字符或默认字符。

-1
string s("type"); 
char c = s.at(0); 
+1

注意'.at(0)'会为空字符串抛出一个'out_of_range'异常。否则,它与'operator []'的行为相同 – AJG85 2012-04-23 19:10:25

5

,如果你已经把一个非空字符串转化map_of_strings["type"]这应该工作。否则,您会收到一个空字符串,并且访问其内容可能会导致崩溃。

如果你不能确定该字符串是否存在,你可以测试:

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

或者,如果你想避免添加一个空字符串到地图:

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] 
    } 
} 

或者你可以使用at做了一系列检查,并抛出一个异常,如果字符串为空:

char type = map["type"].at(0); 

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

char type = map.at("type").at(0); 
相关问题