英文:
Is the actual location where the elements inside the std::vector<std::string> are stored in the heap or stack?
问题
关于 vector<char> 和 vector<int>,char 元素和 int 元素都存储在堆栈中,但是对于 vector<string> 呢?
如果我想存储一个包含许多字符串的大型 vector<string>,我应该使用 new vector<string> 将我的向量存储在堆中吗?
英文:
As for vector<char> and vector<int>, the char elements and the int elements are both stored in the stack,but what about a vector<string>?
If I want to store a huge vector<string> with many strings, should I use new vector<string> to store my vector in the heap?
答案1
得分: 3
你在过度思考这个。
只需使用 vector<string>。它会为你管理分配,并且 sizeof(std::vector<...>) 是固定且合理的。
即使在使用 std::array 的情况下,它更像C数组,包括大小在内,如果需要,std::string 也会使用动态分配。
几乎不需要使用 new std::vector<...>。
英文:
You're over-thinking this.
Just use vector<string>. It manages the allocations for you, and sizeof(std::vector<...>) is fixed and reasonable.
Even then, if you were using std::array which acts a lot more like a C array, size and all, std::string will use dynamic allocation if necessary.
Using new std::vector<...> is hardly ever necessary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论