如何初始化Vector C++的指针?

How to initialized Pointer of Vector c++?

以下代码无效:

vector< vector<int> > *te = new vector<  vector<int> >();     
(*te)[0].push_back(10);      
cout << (*te)[0][0];

我应该如何初始化它?

std::vector<std::vector<int>>* te = new std::vector<std::vector<int>>();

这条线不是你的问题。但是,它确实回避了问题 "Why are you dynamically allocating a std::vector?"

(*te)[0].push_back(10);

这一行是你的问题。您正在访问 te 的第 0th 索引,但它是空的(即,这样做会调用未定义的行为)。您需要先向其中添加一些内容:te->push_back(std::vector<int>());.

示例代码

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int>>* te = new std::vector<std::vector<int>>();

    // Add an empty `vector` to `te`
    te->push_back(std::vector<int>());

    // Add `10` to the first `vector` in `te` and print it
    (*te)[0].push_back(10);
    std::cout << (*te)[0][0];

    delete te;

    return 0;
}

注意:你也应该养成使用智能指针的习惯,不要担心手动new和删除内存(例如,std::unique_ptr指针和std::make_unique).

我认为向量的动态分配没有任何意义,但是正确的语法看起来像

#include <iostream>
#include <vector>

int main() 
{
    std::vector<std::vector<int> > *pv = new std::vector<std::vector<int> >;

    pv->push_back( std::vector<int>( 1, 10 ) );

    std::cout << ( *pv )[0][0] << std::endl;

    delete pv;
}

输出为

10