Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

c++ - Vector of Vector specific syntax

I usually declare (and define) my vector of vectors with the following syntax,

vector<vector<int>> graph = *new vector<vector<int>>(n, *new vector<int>(n, 0));

Here n is already defined. And this usually works fine in most compilers. But a few days ago I tried importing the source file to another system, and it was filled with compilation errors something like,
"Expected primary expression after '>>' "
I do not remember the exact errors, but do know that after adding spaces between '>' and '>' on both sides the error was removed. i.e.

vector<vector<int> > graph = *new vector<vector<int> >(n, *new vector<int>(n, 0));

I know that the syntax requires us to add spaces between both '>'s, but I would like to know if there is any difference between the compilers, because both used c++11 and even the same IDEs. I have used this syntax for very long and it would be very frustrating to edit each one. It would be easier to know which compilers it works on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'll give you a two-part answer:

vector<...> v = *new vector<...>(...)

Basically, you shouldn't do this.
Vector does its own memory management, so there is no need for raw new. Also, in this line you allocate memory for a vector on the heap (which is only 12 or 24 bytes, depending on your system), then assign this vector to the vector v on the stack (which might involve a copy of the contents of the whole vector). The vector on the heap is never deleted and thus the memory is leaked.

Better:

vector<vector<int>> graph = vector<vector<int>>(n, vector<int>(n, 0));

or just

vector<vector<int>> graph(n, vector<int>(n, 0));

Now the answer to your original question: The C++ standard started allowing >> to close nested templates starting from C++11 (see this related question), so you need to configure your compiler to use at least the C++11 standard (normally using the -std=c++11 flag). However, nearly all recent compilers I know already use this standard by default.

For a more detailed answer you would need to tell us which IDE and compiler you use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...