std::stringstream 作为函数的参数 [英] std::stringstream as parameter to a function
问题描述
我有一个 std::vector
并且我希望使用 std::for_each 来遍历这个向量并连接一个字符串,所以我炮制了以下结构:
I have a std::vector<std::string> temp_results
and I wish to use std::for_each to go through this vector and concatenate a string, so I concocted the following construction:
std::stringstream ss;
std::string res = std::for_each(temp_results.begin(), temp_results.end(), boost::bind(addup, _1, ss));
std::string addup(std::string str, std::stringstream ss)
{
ss << str;
ss << ";";
return ss.str;
}
我收到以下错误,这超出了我的理解:
I get the following error, which is beyond my understanding:
error C2475: 'std::basic_stringstream<_Elem,_Traits,_Alloc>::str' : forming a pointer-to-member requires explicit use of the address-of operator ('&') and a qualified name
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Alloc=std::allocator<char>
]
谁能解释一下哪里出了问题?
Could someone please explain what is wrong?
推荐答案
如果,通过编写 return ss.str;
你打算从 str
调用成员函数 str
code>std::stringstream,那么你缺少一对括号:
If, by writing return ss.str;
you intend to call the str
member function from std::stringstream
, then you are missing a pair of parenthesis :
return ss.str();
此外,您的代码可能不会按照您的预期运行.如果您希望每次调用 addup
都在同一个 std::stringstream
实例上工作,则必须通过引用来获取它:修改 addup
签名并在 boost::bind
中的 ss
参数周围添加一个 boost::ref()
.
Also, your code probably won't do what you expect. If you want every call to addup
to work on the same std::stringstream
instance, you have to take it by reference : modify the addup
signature and add a boost::ref()
around the ss
parameter in the boost::bind
.
这是一个工作版本,我认为它可以满足您的期望:
Here is a working version which I presume does what you expect :
void addup(std::string str, std::stringstream &ss)
{
ss << str;
ss << ";";
}
int main()
{
std::vector<std::string> temp_results;
/* ... */
std::stringstream ss;
std::for_each(temp_results.begin(), temp_results.end(), boost::bind(addup, _1, boost::ref(ss)));
std::cout << ss.str() << std::endl;
}
使用 boost::lambda
的替代方法:
std::for_each(temp_results.begin(), temp_results.end(), ss << boost::lambda::_1 << ';');
这篇关于std::stringstream 作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!