std :: vector到带有自定义分隔符的字符串 [英] std::vector to string with custom delimiter

查看:869
本文介绍了std :: vector到带有自定义分隔符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义分隔符将向量的内容复制到一个长的字符串。到目前为止,我尝试过:

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&)’

've try with charT * 但我得到

I've tried with charT* but I get

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

然后我尝试使用 char ostream_iterator< int>(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.

这篇关于std :: vector到带有自定义分隔符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆