我如何 cout 一个向量 [5][1] N 次

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

我正在学习 C++,并且我正在从事一个我有二维向量的项目[5][1]

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

然后我向第二个维度添加一个计数 示例:

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

我想统计第一维和第二维的次数

所以如果我将 vector[0][0] 计算 17 次 vector[1][0] 24 次等等

我 3 周前才开始学习,教授反应迟钝得令人难以置信,所以我将不胜感激所有反馈!

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

我假设你的声明是int vector[5][1](但你应该在你的问题中澄清)。

这意味着第一个维度的有效索引是从 04(含)。对于第二个维度,唯一有效的索引是 0.

当您执行 vector[0][1] 等操作时,您会越界,因此您有未定义的行为。如果你想在第二个维度中存储两个元素,那么你需要 int vector[5][2].


回到你的问题。假设您修复了声明。

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

想一想你会如何连续这样做

cout the first dimension

好的,所以

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

... the second dimension number of times

所以我们重复上述vector[row_idx][1]次。简单易行:

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

现在对每一行执行此操作:

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;
}