C++ 指向向量的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9963453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ pointer to vector
提问by Mukesh
I have to insert elements into a pointer to a vector.I have written the following code but it is giving segmentation fault. Could someone please point out what are the errors in this code or how can we do this alternatively.
我必须将元素插入到指向向量的指针中。我编写了以下代码,但它给出了分段错误。有人可以指出这段代码中的错误是什么,或者我们可以如何做到这一点。
int main()
{
vector<int> *te;
te->push_back(10);
cout<<te->size()<<endl;
return 0;
}
回答by Luchian Grigore
You never allocate the vector:
你永远不会分配向量:
vector<int> *te = new vector<int>;
Also, you don't need dynamic allocation. A cleaner way is with automatic storage:
此外,您不需要动态分配。更简洁的方法是使用自动存储:
int main()
{
vector<int> te;
te.push_back(10);
cout<<te.size()<<endl;
return 0;
}
回答by Ed S.
vector<int> *te;
te->push_back(10);
You have declared a pointer to a vector
; you have not initialized it to point to a valid piece of memory yet. You need to construct a new vector using new
.
您已经声明了一个指向 a 的指针vector
;您尚未将其初始化为指向有效内存。您需要使用 构造一个新的向量new
。
vector<int> *te = new vector<int>();
You should however not do this. There are very few reasons to maintain a pointer to a vector, and you just made it completely ineffective at managing its own internal memory.
但是,您不应该这样做。维护指向向量的指针的原因很少,而且您只是使其在管理自己的内部存储器方面完全无效。
Read a little bit about RAII. This is a technique used to manage dynamically allocated memory via the lifetime of an object. The vector
uses this method to clean up its internal, dynamically allocated storage when it goes out of scope.
阅读一些关于RAII 的内容。这是一种用于通过对象的生命周期管理动态分配的内存的技术。在vector
使用此方法时,它进入的范围进行清理其内部,动态分配存储。
Maintaining a pointer to the vector prevents it from working correctly, relying on you to call delete
yourself, essentially nullifying one major benefit of using a vector
over an array in the first place.
维护一个指向向量的指针会阻止它正常工作,依赖于你delete
自己调用,从本质上来说,首先使用vector
数组的一个主要好处是无效的。
回答by eday
you have to first allocate place for the pointer before starting to use it .
在开始使用它之前,您必须首先为指针分配位置。
vector<int> *te = new vector<int>();
insert this line into your code just after the vector<int> *te;
将此行插入您的代码中 vector<int> *te;
Note that
注意
If you were to trying to access already defined vector with an pointer you would not have to allocate place for the pointer.
如果您尝试使用指针访问已定义的向量,则不必为指针分配位置。
For example;
例如;
vector<int> foo={1,2,3,4,5};
vector<int> * te=&foo;
te->push_back(6); // its legal.