-1

I am generating a string key from a list of integers to store corresponding value in a map. Now i want to regenerate integer list from key. Here is my function to generate key:

void generateKey( const std::vector<unsigned int>& varSet, string& key )
    {
    // Generate a string by concatinating intergers as v_12_34_5
    stringstream varNames;
    varNames <<"v";

    for (unsigned int i = 0; i < varSet.size(); i++) 
        {
        varNames <<"_"<<varSet[i];
        }
    key = varNames.str();
    }

Thanks to help me to write a code for reverse parsing this string key into integers vector.

DataMiner
  • 325
  • 1
  • 3
  • 16
  • 2
    This seems to be covered by several questions showing up in the _Related_ sidebar (eg, [this](http://stackoverflow.com/q/53849/212858) and [this](http://stackoverflow.com/q/276099/212858)). Did you try something and have trouble with it? – Useless Feb 21 '13 at 19:05
  • http://stackoverflow.com/q/236129/1458030 – qPCR4vir Feb 21 '13 at 19:14

2 Answers2

2

In the reverse case, you should ignore the first character and then extract the remaining _<value>s in a loop. Here is a possible solution:

vector<unsigned int> generateKey(string key)
{
  stringstream varNames(key);
  varNames.ignore(); // Ignore the initial v

  vector<unsigned int> varSet;
  unsigned int value;

  // While we can ignore a character and extract an integer, add them
  // to varSet
  while (varNames.ignore() &&
         varNames >> value) {
    varSet.push_back(value);
  }

  return varSet;
}

An alternative solution would be to use std::getline, treating _ as a line delimiter.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

Looks like a was beaten to the punch. Nevertheless: you might want to check that you input is well formed; if so here's a sample program:

#include <iostream>
#include <sstream>
#include <vector>
#include <cassert>

namespace {
  std::vector<unsigned int> parse(std::istream &is) {
     assert(is.get() == 'v');
     std::vector<unsigned int> res;
     while (is.good()) {
      unsigned int tmp;
      assert(is.get() == '_');
      is >> tmp;
      res.push_back(tmp);
    }
    assert(!is.fail());
    return res;
  }

  std::vector<unsigned int> parse(const std::string &s) {
    std::istringstream ss(s);
    return parse(ss);
  }
}

int main(int, char **) {
  for (unsigned int i : parse("v_1_23_4")) {
    std::cout << i << std::endl;
  }
  return 0;
}

I used assertions but you might want to use exceptions or return an error value. HTH

Till Varoquaux
  • 549
  • 5
  • 9