Re: How to make whole container to create in heap
sandeep wrote:
When we use STL which memory space it will use whither it is stack or
heap or data segment
How to make STL to create in heap?
How to make whole container to create in heap?
I think container uses stack is it correct ?
Technically, Standard C++ doesn't discuss heap vs. stack. It refers to
"automatic storage" (which may be on the stack) and "free store" (which
may be a heap or heaps), and it allows compiler implementors to do
things differently for particular architectures in which, e.g., a stack
is not the most efficient implementation.
That being said, all containers use the free store for their containees
(unless you create an allocator to do differently), though the
container itself (e.g., head and tail pointers for std::list) might be
either automatic or dynamically allocated. Consider:
#include <vector>
void Foo()
{
std::vector<int> v1;
std::vector<int>* v2 = new std::vector<int>();
// ...
delete v2;
}
Here v1 and v2 will allocate their data on the free store, but the
housekeeping elements of v1 are automatic (in your case, on the stack)
while those of v2 are on the free store (though the pointer v2 itself
is still an automatic object).
I am using double linked list so in place of it I want to use STL for
Is this a completely separate question?
#include<stdio.h>
#include<iostream>
#include<vector>
using namespace std;
void fun();
void fun1();
vector<int> root;// I want to create this in heap
First, this is not a doubly linked list. std::vector is essentially a
smart array, which means that its insertions and deletions are
expensive. If you need a linked list, you might consider std::list
(compare http://www.sgi.com/tech/stl/List.html).
Second, don't use global variables. Reducing variable scope as much as
possible helps make programs more understandable and robust.
May I suggest you get a good C++ book such as _Accelerated C++_ by
Koenig and Moo?
void main()
int main(). See
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.3.
{
fun();
fun1();
}
void fun1()
{
printf("%d\n",root[1]);
}
Prefer iostreams for type safety, etc. See
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.1.
void fun()
{
root.push_back(55);
root.push_back(66);
}
Cheers! --M