1

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

如果可以从 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);
4

4 回答 4

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);
于 2012-04-23T19:13:19.013 回答
3

c_str() 方法将返回一个指向内部数据的指针。如果字符串为空,则返回指向 NULL 终止符的指针,因此简单的单行代码既安全又容易:

std::string s = "Hello";
char c = *s.c_str();
于 2019-11-01T08:55:17.347 回答
2

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

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

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

于 2012-04-23T19:19:05.567 回答
0
string s("type");
char c = s.at(0);
于 2012-04-23T19:05:46.940 回答