C++ std::inner_product works but shouldn't

151 Views Asked by At

I use std::inner_product to count length of common prefix in 2 strings:

string a = "abcdef", b = "abc";
size_t r = std::inner_product(a.begin(), a.end(), b.begin(), size_t(0),
                              [] (size_t v1, size_t v2) { return v1 + v2; }, 
                              [] (char c1, char c2) { return size_t(c1 == c2); });   

I'd expect that it will work if size of a is less then size of b.
Why does it work if size of a is more then size of b?
Here is a standard implementation (first2 will be invalid while first1 will still be OK):

    template<class InputIt1, class InputIt2, class T>
    constexpr // since C++20
    T inner_product(InputIt1 first1, InputIt1 last1,
                                    InputIt2 first2, T init)
    {
            while (first1 != last1) {
                     init = std::move(init) + *first1 * *first2; // std::move since C++20
                     ++first1;
                     ++first2;
            }
            return init;
    }

Is it a case of unspecified behaviour?
std::inner_product

0

There are 0 best solutions below