指针中的向量是什么意思?

时间:2016-11-29 18:34:42

标签: c++

当我学习polimorphism时,我看到了这样的代码:

Class A {};

int foo(vector<A*> &s){....}

vector<A*>的平均值是什么?vector<A*> &s的平均值是什么?我如何使用foo功能?例如

vector<A> a;
vector<A> b;
vector<A*> p;
p[0]=&a; //Why this is illegal?

foo(p); //Why this is illegal?

我最后的问题是,

vector<A>vector<A*>vector<A>*vector<vector<A>>vector<vector<*A>>

之间的差异是什么?

3 个答案:

答案 0 :(得分:4)

您似乎对此处装饰的类型感到困惑。我将首先解释“什么是装饰类型?”

答案是这样的:C ++中的装饰类型是由附加符号转换的类型。它将类型转换为另一种类型。让我们举个例子:

// The type of a is `int`. The type `int` is not decorated.
int a;

// The type of `b` is lvalue reference of int.
// We decorated int with a `&` to mean that it's a reference to int.
int& b = a;

// The type of `c` is lvalue reference to constant int.
// We decorated `int` with `const&` to mean that it's a reference to int, but constant.
int const& c = a;

// The type of `d` is pointer to int.
// We decorated the type `int` with the `*` to mean that it's a pointer to int.
int* d = &a;
//       ^--- be careful here, the & in front of a variable does
//            not mean it's a reference. We are not decorating a type here,
//            The `&` operator is used to get the address of a variable.

好的,现在您已经知道了如何装饰类型,让我们看看角度braket的含义。你看,std::vector不是一个班级。但是,std::vector<int>是。你不能说“我想要一个清单!”你必须说“我想要一个&lt; that&gt;”的列表。

您必须在尖括号内放置一个类型。在您的情况下,类型为A*A是一个类,A*是一个装饰类型,意思是“指向A的指针”。这意味着您拥有的向量是指向A的指针列表!

现在你知道带有A*的向量意味着什么,阅读你的函数声明很容易:

int foo(vector<A*>& s){....}

s的类型是decoratede类型。它是矢量的参考。但是等等,它是包含一些A*的向量的引用。 A*是用A修饰的*类型,这意味着它是指向A的指针。所以这里我们有一个指向A的指针向量的引用。

  

p[0] = &a;为什么这是非法的?

为了解释原因,我们必须打破部分表达。

    p   [0] = &a
// (1)  (2)   (3)

有三个部分。第一部分是p。什么是p?这是A*的向量,就像之前一样。没什么大不了。

现在(2)部分意味着什么?这是对[]的运营商vector的调用。矢量是一个列表。 []表示我们想要访问列表的特定元素。更具体地说,我们想要访问位置0的元素,因此访问[0]。因此,您可以将整个表达式视为向量的第一个A*。这意味着p[0] A*

让我们再看看你的表情:

      p[0]   =   &a
 // first A* =   (3)

什么是&a?如果你还记得第一个例子,那么&就意味着我们采用变量a的地址。

地址的类型是指针。因此,整个&a表达式的类型为vector<A>*。我想你现在错了。说这个有意义吗?

         p[0]      =         &a
 //     an A*      = a pointer to a vector of A

所以现在。你如何使用函数foo

你看,函数foo需要一个指向A的指针向量的引用。如果你还记得第一个例子:

           int& b           =        a;
//  a reference to an int   =  an int variable

对vector的引用以相同的方式工作:

          std::vector<A*>& b           =           a;
//  a reference to an vector<A*>       =  a vector<A*> variable

因此,为了使你的函数能够工作,你必须发送它所要求的函数:指向A的向量。

std::vector<A*> a;

foo(a);

最后一个提示:给自己一本好的C ++书。您可以在书籍和在线资源中找到所有这些内容。你不太可能再找到像我这样的人,愿意花时间来帮助你,而不是找一本可以解释这一切的好书。

答案 1 :(得分:0)

它们只是表示数组的序列容器。它们的大小可以改变。当你使用foo时。 foo只是您在需要标识符的示例中使用的名称。但是你没有上下文给标识符一个有意义的名字。

答案 2 :(得分:-1)

vector是标准模板库(STL)。它是一个像动态大小的容器一样的数组。您不需要声明像数组一样的大小。它的复杂性就像数组一样。