Clearing a 2d pointer vector of class objects

Hello,
How do I clear a 2d pointer vector of class objects.

Ex: std::vector< vector<SttHit*>* >* vec_layer;

vec_layer->clear();
or
vec_layer->erase (vec_layer->begin(),vec_layer->end());
gives me a segmentation break.
Last edited on
Hello AkshayMalige,

Try vec_layer.clear().

Andy
Hey Andy,

It doesn't work since that is a pointer.
I’d give a second check to my destructor - perhaps there’s something which is not deleted properly.
Just out of curiosity, does a two steps ‘clear()’ works?

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <chrono>
#include <iostream>
#include <vector>
#include <random>


using weird_vec = std::vector<std::vector<int*>*>;


void printWeirdVector(const weird_vec* v);


int main()
{
    constexpr int Max_Vect_Size { 10 };
    std::mt19937 eng {
        static_cast<unsigned>(
            std::chrono::high_resolution_clock::now().time_since_epoch().count()
        )
    };
    std::uniform_int_distribution<> dst(0, Max_Vect_Size - 1);

    weird_vec *vec_layer = new weird_vec(Max_Vect_Size);

    for(auto& a : *vec_layer) {
        a = new std::vector<int*>(Max_Vect_Size);
        for(auto& b : *a) {
            b = new int { dst(eng) };
        }
    }

    // Only for debug: print out the container
    printWeirdVector(vec_layer);

    for(auto& a : *vec_layer) {
        a->clear();
        // a->shrink_to_fit() ?
    }
    vec_layer->clear();
    // vec_layer->shrink_to_fit() ?

    // Is there anything to print out?
    std::cout << "Printing out the container:\n";
    printWeirdVector(vec_layer);
}


void printWeirdVector(const weird_vec* v)
{
    
    for(const auto& a : *v) {
        for(const auto& b : *a) {
            std::cout << *b << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';
}

It would probably be best to eliminate the pointer-to-vector-of-pointers-to-vectors-of-pointers entirely.

Why, in particular, is std::vector<std::vector<SttHit>> not suitable for the use case?
Thank you for your interest mbozzi,

It is quite difficult for me to use just a vector instead of a pointer since i have function that is repeated some million times on this vector which demands a pointer.

Is there any other way to clear it as it is?
It is quite difficult for me to use just a vector instead of a pointer since i have function that is repeated some million times on this vector which demands a pointer.

I don't understand why. You can obtain a pointer to the elements of the vector as required.
Last edited on
Okay, I am not an expert, hence i am taking your suggestion and going ahead with it. I will let you know my results with this. Thank you
Turns out my code works without using pointers. Thank you very much for the idea mbozzi
Topic archived. No new replies allowed.