Declare, define and initialize one-dimensional and two-dimensional arrays (vector container) in Qt C++ (two)

head File

class Vector_test
{
    
    
public:
    Vector_test();

    vector<int> one;
    vector<vector<double> > two;

    vector<int> one_list{
    
    1,2,3};
//    初始化列表的方式(构造函数定义时)给成员变量赋值,是可以的

//    int psize = 1;
//    vector<double> g_best(psize);
//    定义时用的小括号,编译器会认为你尝试定义一个函数。会报错
//    对类的成员函数而言,除了在类体中声明外,还需要在类体外定义。(大部分是这样)

    vector<double> test_1;

    vector<int> two_array_low;
    vector<vector<int> > two_array;
};

Source File

Vector_test::Vector_test()
{
    
    
    vector<int> m;
    qDebug() << m;

    qDebug() << "one" << one;
    qDebug() << "two" << two;

    qDebug() << "one_list" << one_list;

//    qDebug() << "g_best" << g_best();

    test_1.push_back(3.14);
    qDebug() << "test_1" << test_1;


    int k = 1;
    for (int i = 0; i < 3; i++){
    
    
        for (int j = 0; j < 5; j++){
    
    
            two_array_low.push_back(0);
        }
        two_array.push_back(two_array_low);
//       two_array_low.clear();
    }

    qDebug() << "two_array" << two_array;
}

outcome

Int variable is only declared (generally only said declaration, but in fact it is declared and defined together), you can print out the value, but the value printed each time is different because it is a randomly allocated space.
The variable is created but not initialized. The intelligent compiler will initialize by default-automatically allocate the memory address (ie memory unit) for the variable, and print out the value of the corresponding memory, but each time it runs, the allocated address is different, resulting in printing Different values

The default initialization of a two-dimensional array (the output is vector()) can only print out empty, unallocated containers.
If you use at to access members later, it must be initialized, otherwise memory leaks will occur.

std::vector()
one std::vector()
two std::vector()
one_list std::vector(1, 2, 3)
test_1 std::vector(3.14)
two_array std::vector(std::vector(0, 0, 0, 0, 0), std::vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), std::vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

Guess you like

Origin blog.csdn.net/qq_43641765/article/details/111188309