我在这里回答了一个问题:https://stackoverflow.com/a/28862668/2642059我需要使用循环遍历 string
的地方。我想在每个函数上使用 const string&
作为我的参数,但除非我想在每次递归时重建字符串,否则我发现我需要传递 start
和 finish
位置以及 string
本身。所以传递 string
变得毫无意义。
最后,我选择将 start
和 finish
指针传递给 char[]
。
举个例子,假设我得到一个包含嵌套括号的字符串(但没有并排的括号插入)。就像这样:
(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz
但不是这样的:
(abc(def)(ghi)(j)(klm)(nop)(qrs)tuv)wxyz
我想写一个递归程序来提取嵌套最深的括号中的字符串。像这样的东西:
string foo(const string& bar){
auto start = bar.find('(') + 1;
return start == string::npos + 1 ? bar : foo(bar.substr(start, bar.find_last_of(')') - start));
}
但是,我不高兴为 foo
的每次重复重建一个 string
。另一种方法是像链接示例中那样传递 start
和 finish
指针(或传递 string::const_iterator
。)
是否有包装器或其他东西可以让我使用 string
功能,但不能重建 string
?
最佳答案
string_view
来自库基础的 TS 可能是一个想法,GCC 提供支持。
接口(interface)实际上与string
#include <experimental/string_view>
using std::experimental::string_view;
string_view foo(const string_view& bar){
auto start = bar.find('(') + 1;
return start == string_view::npos + 1 ? bar : foo(bar.substr(start, bar.find_last_of(')') - start));
}
最后一行也可以是
return start ? foo(bar.substr(start, bar.find_last_of(')') - start)) : bar;
尽管它们都非常神秘。
关于c++ - 递归传递字符串而不需要重新创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29007753/