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?
vector<Node*>
#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); }
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):
n
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 .
, . , clear() , vector , ( ). vector , , clear() vector. , vector , clear().
clear()
vector
, nitpicker , ++i i++, i++ , ( ). , vector , NULL. , vector, . .
++i
i++
NULL
, .
:
vector<Node>
Source: https://habr.com/ru/post/1756621/More articles:mysql index dimension - mysqlRails - saving search query / result - ruby-on-railsJQuery Validate: custom post not working - jquery-validateClass modifier for automatically generated classes - c #Access command line arguments in C - cJUnit 4.x: why is @Before never executed? - javajQuery - stop hover event while dragging and dropping - jqueryinsert all $ _POST data into mysql using php? - phpHow to insert a new div that surrounds existing elements - javascriptCheck driver license numbers? - jqueryAll Articles