3

I'm loading an ini file with boost property_tree. My ini file mostly contains "simple" types (i.e., strings, ints, doubles, etc.) but I do have some values that represent an array.

[Example]
thestring = string
theint = 10
theintarray = 1,2,3,4,5
thestringarray = cat, dog, bird

I'm having trouble figuring out how to get boost to programmagically load theintarray and thestringarray into a container object like vector or list. Am I doomed to just read it in as a string and parse it out myself?

Thanks!

Tim Reddy
  • 4,340
  • 1
  • 40
  • 77

1 Answers1

7

Yes you are doomed to parse on your own. But it's relatively easy possible:

template<typename T>
std::vector<T> to_array(const std::string& s)
{
  std::vector<T> result;
  std::stringstream ss(s);
  std::string item;
  while(std::getline(ss, item, ',')) result.push_back(boost::lexical_cast<T>(item));
  return result;
}

which than can be used:

std::vector<std::string> foo = 
    to_array<std::string>(pt.get<std::string>("thestringarray"));

std::vector<int> bar =
    to_array<int>(pt.get<std::string>("theintarray"));
Karl von Moor
  • 8,484
  • 4
  • 40
  • 52
  • I'm new to boost...but doesn't split only work with strings? So I can't use this function to populate a `vector`? – Tim Reddy Feb 13 '11 at 22:44
  • @Polybox: actually, I had that exact same code when I asked this question minus the template and lexical_cast...but now that I made the modifications, I get a `no matching function for call` compiler error...the joys of c++... :) – Tim Reddy Feb 14 '11 at 00:05
  • @TReddy: Which function isn't found? I've tested my template and it actually worked fine. – Karl von Moor Feb 14 '11 at 12:30
  • @Polybox: Nothing that you've done...my template is actually in an abstract class so I had to add the impl to the header file as per this discussion: http://stackoverflow.com/questions/1111440/undefined-reference-error-for-template-method – Tim Reddy Feb 14 '11 at 15:10