简体   繁体   中英

How do I cout a vector[5][1] N number of times

I am learning C++ and I am working on a project where I have a two dimensional vector[5][1]

vector[0][0] = 1
vector[1][0] = 2
vector[2][0] = 3
vector[3][0] = 4
vector[4][0] = 5

I then add a count to the second dimension example:

vector[0][1] = 17
vector[1][1] = 24
vector[2][1] = 91
vector[3][1] = 2
vector[4][1] = 50

I want to cout the first dimension the second dimension number of times

So if I would cout vector[0][0] 17 times vector[1][0] 24 times etc.

I just started learning 3 weeks ago and the prof is incredibly unresponsive, so I would appreciate any and all feedback!

I have a two dimensional vector[5][1]

I assume your declaration is int vector[5][1] (but you should clarify in your question).

This means the valid index for the first dimension is from 0 to 4 inclusive. And for the second dimension the only valid index is 0 .

You go out of bounds when you do vector[0][1] etc and as such you have Undefined Behavior. If you wish to store two elements in the second dimension then you need to have int vector[5][2] .


Going back to your question. Assuming you fixed the declaration.

I want to cout the first dimension the second dimension number of times

Think how you would do that for a row

cout the first dimension

ok, so

std::cout << vector[row_idx][0];

... the second dimension number of times

So we repeat the above vector[row_idx][1] times. Easy peasy:

for (int repeat = 0; repeat < vector[row_idx][1]; ++repeat)
{
    std::cout << vector[row_idx][0];
}

And now do this for each row:

std::size_t num_rows = 5;

for (std::size_t row_idx = 0; row_idx < num_rows; ++row_idx)
{
    for (int repeat = 0; repeat < vector[row_idx][1]; ++repeat)
    {
        std::cout << vector[row_idx][0];
    }
    std::cout << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM