tags:

views:

87

answers:

3

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?

+1  A: 

OutputIterators don't allow that. But in your case, what prevent you to return Input1 != Input2?

AProgrammer
This is an example function to illustrate my problem - I'd like to determine whether the output iterator has had anything inserted into it
Alan
Again, you can't. Nothing in the requirement section of OutputIterator allow to do that.
AProgrammer
+1  A: 

You have at least the following two options:

  1. Write your own version inserter which takes an extra boolean reference parameter as an argument which is set to true if cont.insert (...).second is true.
  2. Before the 'if' statement in the caller code, store the size of the container. If it has more elements after the call, then you know that the copy inserted elements.

The second options has potential performance considerations if the cost of size is not O(1).

Richard Corden
+4  A: 

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; }
};
jon hanson