向量特定语法的向量 [英] Vector of Vector specific syntax

查看:86
本文介绍了向量特定语法的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用以下语法声明(并定义)向量的向量

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));

此处n已定义。这通常在大多数编译器中都可以正常工作。但是几天前,我尝试将源文件导入另一个系统,并且它充满了编译错误,例如,

'>>'之后的预期主表达式

我不记得确切的错误,但确实知道在两侧的>和>之间添加空格后,该错误已消除。即

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));

我知道语法要求我们在两个'>之间添加空格,但是我想知道编译器之间是否有区别,因为两者都使用c ++ 11甚至相同的IDE。我使用这种语法已经很长时间了,对每个语法进行编辑将非常令人沮丧。知道使用哪个编译器会更容易。

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.

推荐答案

我将为您提供两部分的答案:

I'll give you a two-part answer:

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

基本上,您不应该

Vector会执行自己的内存管理,因此不需要原始的 new 。另外,在这一行中,您为堆上的向量分配内存(仅12或24个字节,具体取决于您的系统),然后将此向量分配给向量 v 在堆栈上(可能涉及整个向量内容的副本)。堆上的向量永远不会被删除,因此内存会泄漏。

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.

更好:

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

或者只是

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

现在您的原始问题的答案是:C ++标准开始允许> > 关闭从C ++ 11开始的嵌套模板(请参见相关问题),因此您需要将编译器配置为至少使用C ++ 11标准(通常使用-std = c ++ 11标志)。但是,我所知道的几乎所有最新的编译器都已默认使用该标准。

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.

要获取更详细的答案,您需要告诉我们使用的是哪个IDE和编译器。

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

这篇关于向量特定语法的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆