简体   繁体   English

为什么我的多维矢量只有push_back 0索引?

[英]Why does my multidimensional vector only push_back 0 index?

I having a problem using push_back() , I can't figure out why only the first cols vector is just pushed over and over again. 我在使用push_back()遇到问题,我无法弄清楚为什么只有第一个cols向量被一遍又一遍地推送。

Input 输入

10 9 10 3 100 8 7 10 73 9 10 5 9 87 -1 8 3 7 10 92 6 10 6 83 9 11 8 8 77 -1 10 10 10 10 100 10 10 10 100 10 10 10 10 100 -1 DONE


C++ C ++

(...)

size = numbers.size();
counter = 0;
square = ceil(sqrt(size));
vector < vector <int> > rows;
vector<int> cols;

do {
    for (int i = 0; i < square; ++i) {
        cols.push_back(numbers[counter]);
        cout << cols[i] << " ";
        ++counter;
    }
    rows.push_back(cols);
    cout << endl;
} while (counter <= size);
(...)



Undesirable Output 不良输出

0:   10   9  10   3 100   8   7
1:   10   9  10   3 100   8   7
2:   10   9  10   3 100   8   7
3:   10   9  10   3 100   8   7
4:   10   9  10   3 100   8   7
5:   10   9  10   3 100   8   7
6:   10   9  10   3 100   8   7

rows[1][2] should be 73 , not 9 . rows[1][2]应该是73 ,而不是9 Where have I gone wrong? 我哪里出问题了?

You never reset cols . 您永远不会重置cols Instead you just keep adding on to it. 相反,您只是继续添加它。 I think you are printing rows out with magic number indices, which is why you do not spot the added portion. 我认为你是打印rows了与神奇数字指标,这就是为什么你没有发现增加的部分。 Either declare a temporary cols inside the loop or call clear after each push_back() . 在循环内声明一个临时cols或在每个push_back()之后调用clear

awesomeyi found your main problem. awesomeyi找到了您的主要问题。 But your code has other issues too. 但是您的代码也有其他问题。

There is a buffer overflow. 缓冲区溢出。 For example if size == 4 then square == 2 and we get: 例如,如果size == 4那么square == 2 ,我们得到:

  • after iter #1: counter == 2 ; 在迭代#1之后:counter == 2 ; continue since 2 <= 4 从2 <= 4开始继续
  • after iter #2: counter == 4 ; 在#2之后:counter == 4 ; continue since 4 <= 4 因为4 <= 4而继续
  • iter #3: reads numbers[4] and numbers[5] - oops! 迭代3:读取numbers[4]numbers[5] -糟糕!

The loop condition should be: 循环条件应为:

while (counter + square <= size);

we need to make sure that the next iteration will complete without overflowing the vector. 我们需要确保下一次迭代将完成而不会溢出向量。 It would be smart to use .at() for vector access so that if you did make a miscalculation, then the error will behave nicely instead of going screwball. 使用.at()进行矢量访问将很明智,这样,如果您确实进行了错误的计算,则错误将表现得很好而不是像螺丝钉一样。

The loop (minus the output) could actually be written as: 循环(减去输出)实际上可以写成:

for (size_t counter = 0; counter + square <= size; counter += square )
{
    std::vector<int> cols( numbers.begin() + counter, numbers.begin() + counter + square );
    rows.push_back(cols);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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