How could I initialize a two dimensional vector in the contstructor of a class with zero values? This won't work:
#include <vector>
using namespace std;
class matrix {
public:
typed开发者_JS百科ef int element_type;
matrix(int dim):data(dim, vector<int>(dim, 0)) {
}
private:
vector<vector<element_type>> data;
};
Do I have to write a destructor to free the vector?
Update: OP's code is now valid from C++11 onward.
Original answer for earlier versions of C++:
You need to write it like this:
vector< vector<element_type> > data;
because >>
is otherwise parsed as stream operator, which is invalid here. And: No, you do not need to free this in the destructor, because you aren't creating it on the heap.
Do I have to write a destructor to free the vector?
No, because you did not acquire any resources in the constructor. That's the beauty of RAII.
精彩评论