Mat*_*haq 1 c++ string type-conversion c++11
是否有内置的方法来构建std::string基于给定的char?
我问这个的原因是因为我想在if语句中直接进行函数调用:
// Given function prototype
bool func(std::string s);
for(auto rit = s.rbegin(); rit != s.rend(); ++rit)
{
if(func(*rit))
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
std::string(*rit)
static_cast<std::string>(*rit)
Run Code Online (Sandbox Code Playgroud)
自C++ 11以来最简洁的方法是通过初始化列表构建:
func({*rit})
Run Code Online (Sandbox Code Playgroud)
或者如果需要显式指定类型(对于函数模板):
func(std::string{*rit})
Run Code Online (Sandbox Code Playgroud)
对于pre-C++ 11,它是std::string构造函数的第二个重载:
func(std::string(1, *rit))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
689 次 |
| 最近记录: |