开发者

C++, std::copy and templates

开发者 https://www.devze.com 2023-03-08 07:09 出处:网络
I am doing experiments with templates and STL. This is my testing code... template <typename Item>

I am doing experiments with templates and STL. This is my testing code...

template <typename Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <typename Item>
class Cont
{
private:
    typename TList <Item>::Type elements;

public:
    void push_back ( const Item & p ) {elements.push_back ( p );}

    typename TList <Item>::Type ::iterator
        copy (typename TList <Item>::Type ::iterator first,
                typename TList <Item>::Type ::iterator last,
                typename TList <Item>::Type ::iterator result) 
        {
            elements.resize(elements.size() + last - first);  //Exception
            return copy ( first, last, result ); 
        }

        typename TList <Item>::Type ::iterator begin() { return elements.begin(); }
};

But during a copy operation

int main()
{
    Cont <double> cont;
    cont.push_back(1);
    cont.push_back(2);

    TList <double>::Type v;
    v.push_back(3);
    v.push_back(4);
    cont.copy(v.begin(), v.end(), cont.begin());  //Exception
开发者_JS百科    cont.copy(v.begin(), v.end(), cont.end());  //Exception

    return 0;
}

the program causes a runtime exception. Could you help me to find the error?

Exception: Vector iterator + offset out of range...


The expression:

elements.size() + last - first

is evaluated as:

(elements.size() + last) - first

The result of the first addition will be an iterator that exceeds the vector's bounds, which triggers the exception (in debug mode). You could try this:

elements.size() + (last - first)

Or the more STL-like approach:

elements.size() + std::distance(first, last)


The problem is caused by the fact that your copy method resizes the vector, thereby making the iterator you passed it invalid.

0

精彩评论

暂无评论...
验证码 换一张
取 消