-1

我正在从整数列表中生成一个字符串键,以将相应的值存储在地图中。现在我想从键重新生成整数列表。这是我生成密钥的功能:

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

感谢帮助我编写了一个代码,用于将此字符串键反向解析为整数向量。

4

2 回答 2

2

在相反的情况下,您应该忽略第一个字符,然后_<value>在循环中提取剩余的 s。这是一个可能的解决方案:

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

另一种解决方案是使用std::getline, 将_其视为行分隔符。

于 2013-02-21T19:07:24.617 回答
1

看起来像是被打了一拳。尽管如此:您可能想检查您的输入是否格式正确;如果是这样,这是一个示例程序:

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

我使用了断言,但您可能想要使用异常或返回错误值。高温高压

于 2013-02-21T19:55:59.880 回答