How to construct a std::string from a std::vector?

前端 未结 8 1018
南旧
南旧 2020-12-23 02:20

I\'d like to build a std::string from a std::vector.

I could use std::stringsteam, but imagine there is a s

8条回答
  •  礼貌的吻别
    2020-12-23 02:24

    If requires no trailing spaces, use accumulate defined in with custom join lambda.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    
    int main() {
        vector v;
        string s;
    
        v.push_back(string("fee"));
        v.push_back(string("fi"));
        v.push_back(string("foe"));
        v.push_back(string("fum"));
    
        s = accumulate(begin(v), end(v), string(),
                       [](string lhs, const string &rhs) { return lhs.empty() ? rhs : lhs + ' ' + rhs; }
        );
        cout << s << endl;
        return 0;
    }
    

    Output:

    fee fi foe fum
    

提交回复
热议问题