Re: Splitting vector<pair<int,int> > to pair<vector<int>,vector<int>
On Apr 21, 5:18 am, Daniel Kr?gler <daniel.krueg...@googlemail.com>
wrote:
Abhishek Padmanabh schrieb:
On Apr 19, 10:13 am, Daniel Kr?gler <daniel.krueg...@googlemail.com>
There is a second part to that Note :
"[ Note: Unless otherwise specified, algorithms that take function
objects as arguments are permitted to copy those function
objects freely. Programmers for whom object identity is important
should consider using a wrapper class that points
to a noncopied implementation object, or some equivalent solution. -
end note ]"
What would that second part mean?
The second part is related to a situation described in
http://www2.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#92
and can be summarized to the following: Let's assume
you invoke std::remove_if with a functor and you have
the genious idea that you could simply call the invocations
of the functor's operator() call by incrementing a counter
each time to indirectly determine the position ("index")
of the currently checked element. This is not guaranteed
to work by simply adding the count state as normal
member to the functor, because that one could be copied.
Therefore it's recommended that you use an externally
stored state to realize this, where each functor references
this state, e.g. you have to modify the example as shown
below:
class Nth { // function object that returns true for the nth
element
private:
int nth; // element to return true for
int& count; // element counter
public:
Nth (int n, int& count) : nth(n), count(count) {
}
bool operator() (int) {
return ++count == nth;
}
};
Thanks for the explanation, Daniel and the insight on std::set. In
fact, I actually faced the problem owing to wierd problem that came
across me sometime ago. I used 3 techniques:
http://learningcppisfun.blogspot.com/2007/02/functors-with-state-4-alternative.html
The fourth was suggestion that I came across and used a reference
member very nicely in the predicate to keep the state. I guess, that
suffers from this problem then.
But it can be advantagous, if a functor is both CopyConstructible
and Assignable, because both requirements are given by
normal function pointers. So, if you would like to be flexible
enough to use a functor where you would use a function
pointer, both requirements should be fulfilled.
I wonder how that can be advantageous? The problem comes when the
functor has state that has to be maintained while copy/assign -
function pointers cannot have state unless they use a global/static
variable or a reference/pointer to an external object. That shouldn't
be the problem with functors as well. Otherwise, we can use functors
in place of plain functions without needing to have to worry about
that. Since keeping a pointer instead of a reference solves the issue,
I guess that fine enough for now.
Regards.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]