将矢量值作为逗号分隔值存储到字符串中

时间:2011-04-29 14:07:40

标签: c++

如何将函数返回的值作为逗号分隔值存储到字符串中。任何人都可以帮助我吗?

const myVector &vecList = obj.get_List();
vector<myNumVector *>::const_iterator iter;
for (iter= vecList.begin(); iter!= vecList.end(); iter++)
{
  string myNum = (*iter)->get_myNum();
  string myNumList = ? 
  //myNumList should be = drt123,ret34,dfghgd234.... if these are the return values
} //can we achive this by use of some sting functions..?

3 个答案:

答案 0 :(得分:1)

从我发布的链接可以看出,有很多方法可以做到这一点。我相信这是最简单的:

#include <vector>
using std::vector;

#include <string>
using std::string;

#include <boost/assign/list_of.hpp>
using boost::assign::list_of;
namespace ba = boost::assign;

vector<string> victor = list_of
  ("Clarence Oveur")
  ("Roger Murdock")
  ("Victor Basta");

int main() {
  string result;
  for(vector<string>::iterator it = victor.begin();
    it != victor.end();
    ++it) {
    if(it != victor.begin()) {
      result += ", ";
    }
    result += *it;
  }
  cout << result << "\n";
}

<小时/> 编辑:直接翻译到OP的问题:

const myVector &vecList = obj.get_List();
vector<myNumVector *>::const_iterator iter;
string myNumlist;
for (iter= vecList.begin(); iter!= vecList.end(); iter++)
{
  string myNum = (*iter)->get_myNum();
  if(iter!=vecList.begin()) {
    nyNumList += ",";
  }
  myNumList += myNum;
}

<小时/> 编辑:通过从先前的解决方案中删除bool first来简化。

答案 1 :(得分:1)

我不确定这是不是你的意思。

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>

int main () {
        std::vector<int> v;
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);
        v.push_back(4);

        std::stringstream list;
        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(list, ","));

        std::cout << list.str();

        return 0;
}

输出:1,2,3,4,

答案 2 :(得分:0)

是的,这可以使用字符串函数以及其他一些方法来实现。

如果在循环外定义string myNumList,则可以简单地

myNumList += "," + myNum;

虽然这会在beinning中添加一个无关的逗号,所以请检查它是否首先指向那里:

if(iter != vecList.begin())
    myNumList += ',';
myNumList += myNum;