Std :: set for each element of the array

I need the std::set functionality for each element of the array. How can I achieve this functionality?

I started by allocating a dynamic array of std-set in C ++ as follows:

 set<int>* entry; 

followed by highlighting:

 entry = (set<int>*)malloc(sizeof(set<int>)*32); 

There is no compilation problem, but segmentation fails when any element is executed:

 entry[0].insert(23); 

Any help is appreciated.

+4
source share
5 answers

In C ++, you allocate memory with new . The difference from malloc is that the constructor is called to initialize the memory.

 entry = new set<int>[32]; 
+5
source

What about

 #include <set> #include <vector> int main() { std::vector < std::set<int> > entry(32); // std::vector constructor makes 32 calls to std::set<int> constructor entry[0].insert(23); // std::vector destructor makes 32 calls to std::set<int> destructor } 
+11
source

Even if you allocated storage for 32 std::set , you did not initialize this memory range (that is, the constructor of your std::set not called), so the memory you are trying to use in / access is in entry[0].insert (23) will result in undefined behavior.

Mixing C ++ objects with malloc , and this is usually equivalent (I'm tempted to write “always”), which is considered bad practice.

Instead, go to operator new , which will correctly allocate memory and process the design of your object, and also remember delete memory allocated to free memory back to your system (and make the object really destroyed).


The correct way to do this in C ++

Some answers will contain text saying that you are better off using std::vector<std::set> , although this is actually not the answer to your question, so I will leave you with this example fragment

 int main (int argc, char *argv[]) { std::set<int> *entries = new std::set<int> [32]; entries[0].insert (123); delete [] entries; } 
+4
source

This is a good question whose answer is not immediately obvious. The problem is that every set object wants to be initialized before it is used, while your code only allocates raw memory for each set . This fix is:

 #include <vector> #include <set> using std::vector; using std::set; const int N = 32; int main() { vector< set<int> > entry(N); entry[0].insert(23); return 0; } 
+2
source

Do not try to use malloc / calloc / realloc etc. with C ++ classes. Use a new one.

+1
source

All Articles