Re: using find_if/binary_function
In article <1148592243.865503.91720@i40g2000cwc.googlegroups.com>,
Dilip <rdilipk@lycos.com> wrote:
I have a vector of class object pointers that have 2 internal states
(USED or EMPTY). USED is just a way of indicating the element in that
slot has valid state. EMPTY means the element is available for re-use.
I was trying to write some code to locate an used element using find_if
with a custom predicate derived from unary_function. That was pretty
easy. I however wanted something else. If the element cannot be
located, I wanted to return the index of the first (or for that matter
*any*) empty slot. I am trying to do this in one pass without having
to write another predicate to test for empty slots. I was about to
write something like this:
Predicates are not to have state that is the results of a predicate
do not depend on the order of the tests only what the current argumenet
is. So storing a variable in the functor and depending on its value is
techincally illegal. But since you want ANY empty slot, this functor
should work, but is technically in voilation of the standard.
NOT TESTED EXPOSITION ONLY
struct name_is
{
std::string name;
mutable int i,j
name_is(const std::string &a):name(a),i(-1),j(-1){}
bool operator () (const no_op &x) const
{
++i
if(x.myname == "EMPTY_SLOT")
{
j=i;
return false;
}
return x.my_name == name;
}
int empty_slot() {return j;}
};
using this on a vector<no_op>
vector<no_op> data;
name_is foo("blah");
vector<no_op>::iterator it = std::find_if(data.begin(),data.end(),foo);
if(it !=data.end())
{
// data is in vector modify it
}
else
{
if(foo.empty_slot()>=0)
{
data[foo.empty_slot()] = ...;
}
else
{
data.push_back(...);
}
}
Using boost::iterator_adaptor to create an iterator that stores this
information is also possible and legal.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]