vidhya
vidhya

Reputation: 2911

Storing values from a vector to a string as comma seperated values

how can I store the values returned from a function to a string as comma seperated values. Can anyone help me..?

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..?

Upvotes: 1

Views: 4066

Answers (3)

Marco Kinski
Marco Kinski

Reputation: 342

#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;
}

Outputs: 1,2,3,4,

more modern approach, also solving the trailing ","

#include <string>
#include <numeric>
#include <iostream>

int main() {
    const auto v = {1, 2, 3, 4};
    const auto list = std::accumulate(begin(v), end(v), std::string{}, [](const std::string& so_far, const auto& next) {
        return so_far + (so_far.empty() ? "" : ", ") + std::to_string(next);
    });

    std::cout << list;

    return 0;
}

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168866

As can be seen from the links I posted, there are lots of ways to do this. Here is, I believe, the simplest:

#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";
}


EDIT: To translate directly to OP's question:

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;
}


EDIT: Simplified by removing bool first from previous solution.

Upvotes: 1

Cubbi
Cubbi

Reputation: 47488

Yes, this can be achieved using string functions, along with a handful other methods.

Given a string myNumList defined outside the loop, you could simply

myNumList += "," + myNum;

although that would add an extraneous comma in the beinning, so check if iter is pointing there first:

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

Upvotes: 0

Related Questions