vector out of range when converting to short

I have this code:

int main()
{
    std::vector<unsigned char> cVec{ 'a','r','t','u' };
    std::vector<unsigned short>sVec;

    sVec = { reinterpret_cast<unsigned short*>(&cVec[0]), reinterpret_cast<unsigned short*>(&cVec[cVec.size()-1]) };
    for (auto i : sVec)
        std::cout << i << 'n';
    return 0;
}

but when I run it, I have this error:

vector out of range

how can I solve this problem?

thanks

Answer

you are passing pointers to the first and last character to the std::vector constructor. The pointers should be to the first and one after the last character. As the distance between the two pointers you pass isn’t a whole number of shorts the code has undefined behaviour. The following code should fix the problem:

#include <vector>
#include <iostream>

int main()
{
    std::vector<unsigned char> cVec{ 'a','r','t','u' };
    std::vector<unsigned short>sVec;

    sVec = { reinterpret_cast<unsigned short*>(cVec.data()), reinterpret_cast<unsigned short*>(cVec.data() + cVec.size()) };
    for (auto i : sVec)
        std::cout << i << 'n';
    return 0;
}

Note that you can’t use &cVec[cVec.size()] as this too has undefined behaviour.