Why i can't assign value to the 2d vector of char?

I am working on a code that needs vectors of vectors (2d vector) and I am trying to initialize this with ‘.’ with the below code.

vector< vector< char >> vec;
for(int i=0; i < N ; i++)
{
    vector<char> temp('#', N);
    vec.push_back(temp);
}

I also tried

vector< vector < char >> vec;
for(int i=0; i<N ; i++)
{
    vector< char > temp();
    temp.assign('.' , N);
    vec.push_back(temp);
}

My code is assigning value to the vector, but assigned value isn’t ‘.’ but something else. When I tried to print it, it is printing some weird gibberish output.

I also tried the simple way to assign value to my vector and it worked well. Below is the code.

vector< vector < char >> vec;
for(int i=0; i<N ; i++)
{
    vector< char > temp;
    for(int j=0;j<N;j++)
    {
        temp.push_back('#');
    }
    vec.push_back(temp);
}

Why does the first and second code isn’t working similar to third. Or are they meant to be used with integers only and not char.

>Solution :

The problem is that you have supplied the arguments in the wrong order when creating the temp vector.

Replace vector<char> temp('#', N); with

vector<char> temp(N,'#');

Do the same with std::vector::assign.

Leave a Reply