I have a template function that takes the following form:
template < class ITER1, class ITER2 >
bool example(ITER1 Input1, ITER1 Input2, ITER2 Output)
{
ITER2 OrigOutput(Output);
// ...
std::copy(Input1, Input2, Output);
return (OrigOutput != Output);
}
And I'm calling example()
like this:
std::vector < int > Input;
std::set < int > Output;
if (example(Input.begin(), Input.end(), inserter(Output, Output.begin())))
{
...
}
I'd like example()
to return true
if elements have been inserted into Output
, however I'm getting a compile error (msvc 2008):
Error 1 error C2678: binary '!=' : no operator found which takes a left-hand
operand of type 'std::insert_iterator<_Container>' (or there is no acceptable
conversion)
Is there a way I can determine whether any elements were inserted into the output iterator in order to return the correct bool value?
Write a wrapper iterator which delgates to another iterator, which you would construct from your insert iterator. Your delegate then can set a modified
member to be true in the operator=
method.
Something along the lines of this:
template<typename ITER>
class ModifiedIterator : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
protected:
typedef ITER Iter;
Iter iter;
bool& isModified;
public:
explicit ModifiedIterator (Iter i, bool& isMod)
: iter(i), isModified (isMod)
{}
template<typename T>
ModifiedIterator& operator= (const T& value)
{
iter = value;
++iter;
isModified = true;
return *this;
}
ModifiedIterator& operator* () { return *this; }
ModifiedIterator& operator++ () { return *this; }
ModifiedIterator operator++ (int) { return *this; }
};
OutputIterators don't allow that. But in your case, what prevent you to return Input1 != Input2
?
You have at least the following two options:
inserter
which takes an extra boolean reference parameter as an argument which is set to true if cont.insert (...).second
is true. The second options has potential performance considerations if the cost of size is not O(1).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.