32

我有一个程序,它预计将几个选项作为输入,以 (p1, p2, p3, ... ) 的形式指定概率。所以命令行用法实际上是:

./myprog -dist (0.20, 0.40, 0.40)

我想在 C++ 中解析这样的列表,我目前正在尝试使用 std::string 类型的迭代器和 Boost 提供的 split 函数来完成它。

// Assume stuff up here is OK
std::vector<string> dist_strs; // Will hold the stuff that is split by boost.
std::string tmp1(argv[k+1]);   // Assign the parentheses enclosed list into this std::string.

// Do some error checking here to make sure tmp1 is valid.

boost::split(dist_strs,  <what to put here?>   , boost::is_any_of(", "));

注意上面的<what to put here?>部分。因为我需要忽略开头和结尾的括号,所以我想做类似的事情

tmp1.substr( ++tmp1.begin(), --tmp1.end() )

但它看起来不像这样substr工作,我在文档中找不到可以做到这一点的函数。

我的一个想法是做迭代器算术,如果允许的话,并substr用来调用

tmp1.substr( ++tmp1.begin(), (--tmp1.end()) - (++tmp1.begin()) )

但我不确定这是否被允许,或者这是否是一种合理的方式。如果这不是一种有效的方法,那么更好的方法是什么?...提前谢谢了。

4

1 回答 1

65

std::string的构造函数应该提供你需要的功能。

std::string(tmp1.begin() + 1, tmp1.end() - 1)
于 2012-04-04T03:11:39.617 回答