简体   繁体   中英

Is it possible to have string functions (such as strstr ) consider an array from end towards beginning in C++?

I was wondering whether or not some of the functions in C++ can work "in reverse" . By reverse I mean: opposite to how they normally "traverse" an array. For instance, I know that strchr returns a pointer to the first occurence of given character in the array, whereas strRchr returns last occurence of given character in an array. Do strtok, strstr and any others have the same ability? I believe such options would be very useful, eg : when trying to find largest palindrome; (not sure this is an adequate example...)

Not really, no.

The old C functions take a "start pointer", and most progress forwards until they hit a null terminator. That's fixed behaviour.

If you're lucky, they take a "start pointer" and a length, which is better in some ways, but also mandates a forward traversal unless the function was specifically written not to do one.

Fortunately, C++'s more modern algorithms take iterator pairs to specify a range, which opens up some opportunities. The true magic is that "reverse iterators" exist, things that can be ++ 'd but actually go backwards into a range instead (which is something no category of pointer knows how to do). You are usually permitted to pass reverse iterators into standard algorithms to get the behaviour you want; it's all quite deliberately abstract.

I recommend reading up about C++'s algorithms, and dropping old C tech. Though C programmers certainly still exist (and C applications still, for good reason, exist), the rest of us moved on from such limitations long ago. ;)

No, but you can do an in place reverse() of your array first, and then apply the function you want.

http://www.cplusplus.com/reference/algorithm/reverse/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM