在 C++11 中,为此创建自己的搜索函数很容易。
template<class iter1, class iter2>
iter1 search(iter1 stackbegin, iter1 stackend, iter2 needlebegin, iter2 needleend)
{return std::search(stackbegin, stackend, needlebegin, needleend);}
template<class iter1, class needlecontainer>
iter1 search(iter1 stackbegin, iter1 stackend, const needlecontainer& needle)
{return std::search(stackbegin, stackend, std::begin(needle), std::end(needle));}
template<class stackcontainer, class needlecontainer>
decltype(std::begin(std::declval<stackcontainer>()))
search(const stackcontainer& stack, const needlecontainer& needle)
{return std::search(std::begin(stack), std::end(stack), std::begin(needle), std::end(needle));}
template<class stackcontainer, class needlecontainer>
decltype(std::begin(std::declval<stackcontainer>()))
search(stackcontainer& stack, const needlecontainer& needle)
{return std::search(std::begin(stack), std::end(stack), std::begin(needle), std::end(needle));}
并使用它们:
int main() {
std::vector<char> str1;
auto it = search(str1, "Look for this");
}
编译证明:http: //ideone.com/cO1rz(这个版本的 gcc 没有std::begin
,std::end
所以我必须自己定义它们)和 C++03 版本:http: //ideone.com/gt1Do
如果你真的真的很想要一个简短的宏,你可以保证文字共享相同的空间:
template<int N>
const char* end(const char(&s)[N]) {return s+N;}
#define STR_ITERATORS(X) X, end(X) //BE WARNED, HIGHLY UNSAFE, NOT PORTABLE