如何动态创建向量并将其存储为指针向量?

huangapple go评论81阅读模式
英文:

How to create vector on the fly and store it as vector of pointers?

问题

Approach 1:(在访问时崩溃)

std::vector<std::vector<int> *> vecofvec;
std::vector<int> temp;
vecofvec.push_back(&temp);

Approach 2:(正常工作)

std::vector<std::vector<int> *> vecofvec;
vecofvec.push_back(new std::vector<int>);

我理解第一种方法崩溃是因为我创建的向量是局部的并且超出了范围,但我想知道是否有避免使用new(动态分配)的方法?此外,我不想使用智能指针。

英文:

I want to create vector on the fly and store it inside another vector as pointers. I am trying below 2 approaches.

Approach 1: (crashing while accessing)

std::vector&lt;std::vector&lt;int&gt; *&gt; vecofvec;
std::vector&lt;int&gt; temp;
vecofvec.push_back(&amp;temp);

Approach 2: (Working)

std::vector&lt;std::vector&lt;int&gt; *&gt; vecofvec;
vecofvec.push_back(new std::vector&lt;int&gt;);

I understand that first one is crashing because the vector i am creating is local and going out of scope but
I want to know if there is any way to avoid new (dynamic allocation) ? Also, i do not want to use smart pointers.

答案1

得分: 2

方法1崩溃是因为你存储了一个指向在函数退出后被销毁的局部向量的指针。

这会在向量中动态创建向量。你不关心向量的生命周期。

std::vector<std::vector<int>> vecofvec;
vecofvec.emplace_back();

我想保持效率,所以我不存储向量本身,因为它会复制整个向量,这似乎是低效的。

这是错误的信息。它不会复制,而是以高效方式移动向量。

英文:

The approach 1 is crashing because you store a pointer to a local vector that is destroyed after the function exit.

This creates vectors in the vector on the fly. You don't care of a vector life time.

std::vector&lt;std::vector&lt;int&gt;&gt; vecofvec;
vecofvec.emplace_back();

> I want to keep it efficient so i am not storing the vector itself because it copies whole vector which seems inefficent.

This is wrong information. It does not copy, it moves vectors efficiently.

huangapple
  • 本文由 发表于 2023年7月3日 13:12:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定