how to declare class with 1000000 elements c++

元气小坏坏 提交于 2020-01-03 05:48:10

问题


I am writing a c++ code and my need is to declare a class having two elments as

class arr{
    public:
        long num;
        string str;
};

now i need to store almost 1000000 elments of this class(depending on user input number of class object can warry in a range of 1 <= n <= 1000000 The object are created dynamically as

#include <iostream>
#include<string>

using namespace std;

class arr{
    public:
        long i;
        string str;
};

int main(){
    long n,j,i;
    cin>>n;
    arr a[n];

.... rest of programme

but if value of n is large then 100000 then programs hang but works fine for value less then 100000 what approach should i try to declare more than 100000 objects in a go i tried solving issue with help of 2D array that is dividing arra in two part

arr a[1000][1000];

but this approach is not working for me

please if anybody have any idea do help me out with this thanks in advance


回答1:


Just use std::vector

#include <iostream>
#include <vector>

int main(){
    long n;
    cin>>n;
    std::vector<arr> a(n);
}



回答2:


what approach should i try to declare more than 100000 objects?

is to declare them on the heap not on the stack, you're declaring 1000000 object on the stack, that's toooooo much. Be careful, there's stack limit:

C/C++ maximum stack size of program

why is stack memory size so limited?

to declare them on the heap, use:

arr *arr= new arr[n];

that's the same mechanism the vector uses to initialize elements.




回答3:


Here is some background information on why allocating too large objects on the stack fails with a segmentation fault, while the same amount of space may be allocated on the stack in many small chunks:

The mechanic is, that the system sets up the stack with a small amount of memory allocated. This allocation is guarded by an inaccessible memory region. Whenever the program accesses this inaccessible region, the hardware alarms the kernel; the kernel analyses the situation, deduces that the program needs more stack memory, grows the stack by a few memory pages, and tells the hardware to normally continue executing the program.

This works perfectly as long the accessed address is close enough to the top of the stack, so that the kernel may safely assume that the application indeed wanted to draw up a new stack frame, instead of accessing some random memory location due to a bug. In your case, the limit seems to be around 16 MiB.

You should be able to use much more than 16 MiB of memory, if none of your stack frames is larger than 16 MiB, because then the limit will be raised in many small step, and the system won't think that you just accessed a random location.



来源:https://stackoverflow.com/questions/19197933/how-to-declare-class-with-1000000-elements-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!