我在这里回答了一个问题:https://stackoverflow.com/a/28862668/2642059我需要在哪里使用重复来遍历 string
.我想在每个函数上使用 const string&
作为我的参数,但是除非我想在每次递归时重建字符串,否则我发现我需要传递一个 start
和 finish
位置以及 string
本身.所以传递 string
变得毫无意义.
I answered a question here: https://stackoverflow.com/a/28862668/2642059 Where I needed to use recurrence to step through a string
. I wanted to use a const string&
as my parameter on each function, but unless I wanted to reconstruct the string each recursion I found that I needed to pass a start
and finish
position as well as the string
itself. So it became pointless to pass the string
at all.
最后我选择只将 start
和 finish
指针传递给 char[]
.
In the end I choose to just pass a start
and finish
pointer to the char[]
.
举个例子,假设我得到一个包含嵌套括号的字符串(但没有并排插入括号.)就像这样:
As an example, say that I'm given a string which contains nested parenthesis (but no side by side parenthetical insertions.) So like this:
(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz
(abc(def(ghi((j)klm)nop)qrs)tuv)wxyz
但不是这样:
(abc(def)(ghi)(j)(klm)(nop)(qrs)tuv)wxyz
(abc(def)(ghi)(j)(klm)(nop)(qrs)tuv)wxyz
我想编写一个递归程序来提取最深嵌套括号中的字符串.类似的东西:
I want to write a recursive program to extract the string in the deepest nested parentheses. Something like:
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
s.)
However I'm unhappy reconstructing a string
for each recurrence of foo
. The alternative is to pass start
and finish
pointers as in the linked example (or to pass string::const_iterator
s.)
是否有包装器或其他东西可以让我使用 string
功能,但不能重建 string
?
Is there a wrapper or something which would allow me to use string
functionality, but not reconstruct a string
?
string_view
来自库基础知识 TS 可能是一个想法,在 GCC 中提供支持.
string_view
from the library fundamentals TS might be one idea, support is available in GCC.
接口实际上与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;
虽然它们都很神秘.
这篇关于递归地传递一个字符串而不需要娱乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!