【问题标题】:How to initialized Pointer of Vector c++?如何初始化向量c ++的指针?
【发布时间】:2016-02-03 16:06:32
【问题描述】:

以下代码不起作用:

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

我应该如何初始化它?

【问题讨论】:

  • 您确定需要动态分配向量吗?
  • 如何编写不可维护的代码...
  • 是的 Juanchopanza...

标签: c++ vector operator-overloading


【解决方案1】:

我看不出动态分配向量的意义,但是正确的语法看起来像

#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

【讨论】:

  • @H.Golden 完全不,我们初学者应该互相帮助。:)
【解决方案2】:

std::vector&lt;std::vector&lt;int&gt;&gt;* te = new std::vector&lt;std::vector&lt;int&gt;&gt;();

这条线不是你的问题。然而,它确实引出了一个问题“你为什么要动态分配std::vector?”

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

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

示例代码

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多