問題描述
我在這里回答了一個問題:https://stackoverflow.com/a/28862668/2642059我需要在哪里使用重復(fù)來遍歷 string
.我想在每個函數(shù)上使用 const string&
作為我的參數(shù),但是除非我想在每次遞歸時重建字符串,否則我發(fā)現(xiàn)我需要傳遞一個 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[]
.
舉個例子,假設(shè)我得到一個包含嵌套括號的字符串(但沒有并排插入括號.)就像這樣:
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
的每次重復(fù)重建一個 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
來自庫基礎(chǔ)知識 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;
雖然它們都很神秘.
這篇關(guān)于遞歸地傳遞一個字符串而不需要娛樂的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!