简体   繁体   中英

std::stringstream as parameter to a function

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?

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();

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

An alternative using boost::lambda :

std::for_each(temp_results.begin(), temp_results.end(), ss << boost::lambda::_1 << ';');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM