std::vector 到带有自定义分隔符的字符串

2021-12-21 00:00:00 string vector c++

我想使用自定义分隔符将 vector 的内容复制到一个长 string 中.到目前为止,我已经尝试过:

I would like to copy the contents of a vector to one long string with a custom delimiter. So far, I've tried:

// .h
string getLabeledPointsString(const string delimiter=",");
// .cpp
string Gesture::getLabeledPointsString(const string delimiter) {
    vector<int> x = getLabeledPoints();
    stringstream  s;
    copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter));
    return s.str();
}

但我明白了

no matching function for call to ‘std::ostream_iterator<int, char, std::char_traits<char> >::ostream_iterator(std::stringstream&, const std::string&)’

我试过 charT* 但我得到

I've tried with charT* but I get

error iso c++ forbids declaration of charT with no type

然后我尝试使用 charostream_iterator(s,&delimiter)但我在字符串中得到了奇怪的字符.

Then I tried using char and ostream_iterator<int>(s,&delimiter) but I get strange characters in the string.

谁能帮我理解编译器在这里的期望?

Can anyone help me make sense of what the compiler is expecting here?

推荐答案

使用 delimiter.c_str() 作为分隔符:

Use delimiter.c_str() as the delimiter:

copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter.c_str()));

那样,你会得到一个 const char* 指向字符串,这是 ostream_operator 期望从你的 std::string 得到的.

That way, you get a const char* pointing to the string, which is what ostream_operator expects from your std::string.

相关文章