Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c++ - Pass a string Recursively without Recreation

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.

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

But not like this:

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

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_iterators.)

Is there a wrapper or something which would allow me to use string functionality, but not reconstruct a string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

string_view from the library fundamentals TS might be one idea, support is available in GCC.

The interface is virtually identical to 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));
}

The last line could also be

return start ? foo(bar.substr(start, bar.find_last_of(')') - start)) : bar;

Although they're both pretty cryptic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...