#include<iostream>
#include<vector>
#include<string>
using namespace std;
//find the begin and end pointer instead of iterator
//just for general function myfind defined blow.
//so you can search your element in both array and standard container .. vector
template <typename elemType>
inline const elemType* begin( const vector<elemType> &vec )
{
return vec.empty() ? 0 : &vec[0];
}
template <typename elemType>
inline const elemType* end( const vector<elemType> &vec )
{
//make sure that the next address of the end of the vec
//not &vec[vec.size()-1] but &vec[vec.size()]
return vec.empty() ? 0 : &vec[vec.size()];
}
template <typename elemType>
const elemType* myfind( const elemType *first,
const elemType *last,
const elemType &value )
{
if( !first || !last )
{
return 0;
}
for( ; first != last; ++first )
{
if( *first == value )
{
return first;
}
}
return 0;
}
int main()
{
vector<string> svec;
svec.push_back("iloveyou");
string iloveyou("iloveyou");
// make sure that convert iterator to pointer to limit the arrange
const string* result = myfind( begin( svec ), end(svec), iloveyou );
cout << *result <<endl;
system("pause");
return 0;
}
本文介绍了一种在C++中利用指针而非迭代器进行数组或标准容器(如vector)内元素查找的方法。定义了通用的myfind函数,并通过示例展示了如何在字符串向量中查找特定字符串。
5583

被折叠的 条评论
为什么被折叠?



