Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading