c++c++11typesstdvector

C++ Error when inserting `std::vector<unsigned int>` in `std::vector<std::vector<int>>` but not for `unsigned int` into `std::vector<int>`


The following does not produce an error when compiling:

std::vector<int> vectest = {};
unsigned int a = 3;
vectest.push_back(a);

This is valid as well:

std::vector<unsigned int> vectest = {};
int a = 3;
vectest.push_back(a);

While this does produce an error:

std::vector<std::vector<int>> matrtest = {};
std::vector<unsigned int> vectest2 = {1};
matrtest.push_back(vectest2);

Error:

error: no matching function for call to 'std::vector<std::vector<int>>::push_back(std::vector<unsigned int>&)'

And this one as well:

std::vector<std::vector<unsigned int>> matrtest = {};
std::vector<int> vectest2 = {1};
matrtest.push_back(vectest2);

Error:

error: no matching function for call to 'std::vector<std::vector<unsigned int>>::push_back(std::vector<int>&)'

What is the logic behind ?

I'm using C++ 11


Solution

  • An int can be converted to an unsigned int and vice-versa.

    This is why you can push_back an int into a vector of unsigned int and vice-versa.

    But std::vector<int> and std::vector<unsigned int> are completely unrelated types, and there is no out-of-the-box conversion between them.
    (This is true for any two instatiations of the templated std::vector with different element types).

    Therefore you can't push_back one into a vector of the other.

    As @TedLyngmo commented, what you can do instead is use std::vector::emplace_back, together with std::vector constructor that accepts iterators:

    std::vector<std::vector<int>> matrtest1 = {};
    std::vector<unsigned int> vectest21 = {1};
    matrtest1.emplace_back(vectest21.begin(), vectest21.end());
    
    std::vector<std::vector<unsigned int>> matrtest2 = {};
    std::vector<int> vectest22 = {1};
    matrtest2.emplace_back(vectest22.begin(), vectest22.end());
    

    Live demo

    Note:
    You mentioned you use C++11. Note that the above (regarding the unrelated types etc.) holds for newer versions of C++ as well (in case you'll considered to upgrade).