Wednesday, May 20, 2009

Delete string vector item with find_if function

To use find_if, we may need to supply c++ utility function such as less,
however, this function normally only support primitive, to support custom type we may need to supply own user function, below code show us how build the custom function.



// functional_bind1st.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
#include <strstream>

using namespace std;

class strequal
{
public:
strequal(char* ptr)
{
strcpy(str,ptr);
}
bool operator() (string& ptr)
{
if(!strcmp(str,ptr.c_str()))
{
return true;
}
else
{
return false;
}
}

private:
char str[100];

};

int main()
{
vector v1;
vector::iterator Iter;

int i;
for (i = 0; i <= 5; i++)
{
string abc;
std::strstream abc_stream;
abc_stream << i << '\0';
abc = abc_stream.str();
v1.push_back(abc);
}

cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << (*Iter).c_str() ;
cout << ")" << endl;

char* data="1";

Iter = find_if(v1.begin(),v1.end(),strequal(data));
if(Iter!=v1.end())
{
v1.erase(Iter);
}

cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << (*Iter).c_str() ;
cout << ")" << endl;

return 0;
}

No comments: