英文:
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<std::vector<int> *> vecofvec;
std::vector<int> temp;
vecofvec.push_back(&temp);
Approach 2: (Working)
std::vector<std::vector<int> *> vecofvec;
vecofvec.push_back(new std::vector<int>);
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<std::vector<int>> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论