Add elements and clear pointer vector in C ++

I would like to add 2 elements in vector<Node*>and then clear all the elements and free up memory.
Does this code match the correct path?

#include <stdlib.h>
#include <iostream>
#include <vector>

using namespace std;

class Node {
public:
    int value;
    // ...and some other fields and methods...
};

int main(int argc, char** argv) {
    Node* n = new Node;
    n->value = 20;
    vector<Node*> v;
    v.push_back(n);
    n = new Node;
    n->value = 52;
    v.push_back(n);
    for (vector<Node*>::iterator i = v.begin(); i != v.end(); i++) {
        cout << (*i)->value << endl;
        delete *i;
        *i = NULL;
    }
    v.clear();
    return (EXIT_SUCCESS);
}
+3
source share
3 answers

I'm fine. There are a few things that I would change (subjectively):

*i = NULL;  // This is unnecessary.

Then I would avoid reuse n(in fact, I would completely avoid it):

v.push_back(new Node);
v.back()->value = 20;
v.push_back(new Node);
v.back()->value = 52;

In addition, you can consider smart pointers to track your memory. See shared_ptr and ptr_vector .

+8
source

, . , clear() , vector , ( ). vector , , clear() vector. , vector , clear().

, nitpicker , ++i i++, i++ , ( ). , vector , NULL. , vector, . .

+5

, .

:

  • stdlib.h ++ - cstdlib.
  • vector<Node>, ; , .
+3
source

Source: https://habr.com/ru/post/1756621/


All Articles