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

新手上路,请多包涵

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

 // .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* 但我明白了

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

然后我尝试使用 charostream_iterator<int>(s,&delimiter) 但字符串中出现了奇怪的字符。

任何人都可以帮助我理解编译器在这里的期望吗?

原文由 nkint 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 991
2 个回答

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

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

这样,您会得到一个 const char* 指向字符串,这就是 ostream_operator 对您的 std::string --- 的期望。

原文由 jpalecek 发布,翻译遵循 CC BY-SA 3.0 许可协议

绝对不需要超级花哨的东西。像这样简单的东西会取得相同的结果。

 int vectorCounter=0;

//this is where you loop over the contents of your vector
for (auto it = StrVec.begin(); it != StrVec.end(); ++it){

    vectorCounter++;

    //this print contents of the vector
    cout << *it;

    //this will put a custom delimiter
    if (vectorCounter < StrVec.size())
    {
        //This is where you define your delimiter
        cout << ",";
    }
}//end-for-loop

OUTPUT:
1,2,3,4

原文由 Sam B 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题