Adham Zahran
Adham Zahran

Reputation: 2180

returned iterator has the wrong value

I'm just trying to create wrapper functions around some std algorithm functions that I use frequently like find and find_if and others.

But for some reason when I use my wrapper function the returned iterator has the wrong value.

This code fails:

template<typename Container, typename ElementType>
typename Container::const_iterator
find(Container c, const ElementType& e)
{
    return std::find(std::begin(c), std::end(c), e);
}

template <typename T, typename Container>
bool
within_container(const T& element, const Container& v)
{
    return find(v, element) != v.end();
}

int
main()
{
    std::vector<int> v = {1, 2, 3, 4, 5};
    int key = 10;
    bool res  = within_container(key, v);
    assert(res == false);
}

while this code runs fine:

template <typename T, typename Container>
bool
within_container(const T& element, const Container& v)
{
    return std::find(std::begin(v), std::end(v), element) != v.end();
}

int
main()
{
    std::vector<int> v = {1, 2, 3, 4, 5};
    int key = 10;
    bool res  = within_container(key, v);
    assert(res == false);
}

What am I missing?

I'm compiling with g++7.3 on ubuntu 18.04.

Upvotes: 1

Views: 130

Answers (1)

M.M
M.M

Reputation: 141544

This find function template takes c by value and returns iterators to an object that is destroyed when the function returns, leading to undefined behaviour in the caller.

It could be fixed by using Container&& c (a forwarding reference) as the parameter.

Upvotes: 1

Related Questions