【问题标题】:Inline char to std::string conversion内联 char 到 std::string 的转换
【发布时间】:2015-06-24 04:50:55
【问题描述】:

是否有基于给定char 构造std::string 的内置方法?

我之所以问这个是因为我想直接在if 语句中进行函数调用:

// Given function prototype
bool func(std::string s);

for(auto rit = s.rbegin(); rit != s.rend(); ++rit)
{
    if(func(*rit))
    {
        //
    }
}

我尝试了以下方法:

std::string(*rit)
static_cast<std::string>(*rit)

【问题讨论】:

  • 只需要写一个函数来处理字符而不是字符串

标签: c++ string c++11 type-conversion


【解决方案1】:

自 C++11 以来最简洁的方式是通过初始化列表构造:

func({*rit})

或者如果您需要显式指定类型(对于函数模板):

func(std::string{*rit})

对于 C++11 之前的版本,它是 std::string's constructor 的第二次重载:

func(std::string(1, *rit))

【讨论】:

  • 在C++11中可以写func({rit, rit+1});
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 2011-06-11
  • 2019-01-30
  • 2018-08-23
  • 2013-07-18
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多