简体   繁体   English

在向量运算c ++上获取随机数

[英]Getting random numbers on vector operation c++

I'm getting weird numbers as output in this code :我在这段代码中得到了奇怪的数字作为输出:

#include <iostream> 
#include <vector> 

int main(){

    std::vector<std::vector<int>> vec = {{0,1},{2,3}};
    
    vec.push_back({4,5});
    vec.push_back({5,6});

    for (int i = 0; i < vec.size(); i++){
        for (int i2 = 0; i2 < vec.size(); i2++){
            std::cout << vec[i][i2] << std::endl; 
        }
    }


    return 0;
}

It's returning to me:它回到我身边:

0
1
1280136264
0
2
3
347673833
38962
4
5
297276653
134256690
5
6
280499436
268474418

I just want to know how to do it properly, and why I'm getting these numbers.我只想知道如何正确地做到这一点,以及为什么我会得到这些数字。

The output you are seeing is due to undefined behavior in your code.您看到的输出是由于代码中未定义的行为

The outer vector object has 4 inner vector<int> objects added to it.外部vector对象添加了 4 个内部vector<int>对象。 Each of those inner vector<int> objects is holding 2 int values.这些内部vector<int>对象中的每一个都持有 2 个int值。

Your inner for loop is going out of bounds of the inner vector<int> objects, by trying to access 4 int values when there are only 2 int values available.当只有 2 个int值可用时,通过尝试访问 4 个int值,您的内部for循环超出了内部vector<int>对象的范围。

In your inner for loop, you need to change vec.size() to vec[i].size() instead, eg:在您的内部for循环中,您需要将vec.size()更改为vec[i].size() ,例如:

#include <iostream> 
#include <vector> 

int main(){

    std::vector<std::vector<int>> vec = {{0,1},{2,3}};
    
    vec.push_back({4,5});
    vec.push_back({5,6});

    for (size_t i = 0; i < vec.size(); ++i){
        for (size_t i2 = 0; i2 < vec[i].size(); ++i2){
            std::cout << vec[i][i2] << std::endl; 
        }
        /* alternatively:
        auto &vec2 = vec[i];
        for (size_t i2 = 0; i2 < vec2.size(); ++i2){
            std::cout << vec2[i2] << std::endl; 
        }
        */
    }

    return 0;
}

Online Demo在线演示

That being said, a safer way to code this is to use range-for loops instead, eg:话虽如此,更安全的编码方法是使用range-for 循环,例如:

#include <iostream> 
#include <vector> 

int main(){

    std::vector<std::vector<int>> vec = {{0,1},{2,3}};
    
    vec.push_back({4,5});
    vec.push_back({5,6});

    for (auto &vec2 : vec){
        for (auto value : vec2){
            std::cout << value << std::endl; 
        }
    }

    return 0;
}

Online Demo在线演示

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

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