Java-like lastIndexOf in c++

≯℡__Kan透↙ 提交于 2019-12-11 06:25:43

问题


I performed some research on boost and c++ but could not locate anything relevant to my question. Is there an boost library or STL function that implements lastIndexOf?


回答1:


std::string has the member function rfind() which searches from the end and returns the index if found or std::string::npos if not. From the linked reference page:

Finds the last substring equal to the given character sequence.




回答2:


It looks like you might want std::string::find_last_of.

Finds the last character equal to one of characters in the given character sequence. Returns the position of the found character or npos if no such character is found.

Edit:

Also see hmjd's answer. There are differences between find_last_of and rfind depending on whether you are searching for a single character, one of many possible characters, or a substring.




回答3:


Sure, you can use std::find with reverse_iterators. For example, you have a vector of ints and you want to find the last 5 in it. You do

auto it = std::find(v.rbegin(), v.rend(), 5);

If you want the index per se, then you can get that from the iterator

int index = std::distance(v.begin(), (it+1).base());


来源:https://stackoverflow.com/questions/15557700/java-like-lastindexof-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!