如何将数组添加到列表中

How do I add an array to a list?

本文关键字:列表 添加 数组      更新时间:2023-10-16

我有一个名为顶点的数组,它的声明如下:

  CPoint vertices[11];

然后我有一个名为_m_ElementList_的列表

  std::list<CPoint[11]> m_ElementList;

使用 AddElement() 我想将元素添加到此列表中,每个元素都是 CPoint 对象的数组(即与顶点类型相同)

void AddElement(CPoint* vertices)
   { m_ElementList.push_back(vertices); }

由于某种原因这不起作用,它告诉我没有函数的实例与参数列表匹配 - 为什么会这样,我该怎么办?

使用原始数组和指针的想法一开始是错误的。您已经在使用std::list(即您似乎了解标准容器),那么为什么不也使用std::vector<CPoint>呢?这会让你的生活变得轻松:

std::list<std::vector<CPoint>> m_ElementList;

然后:

void AddElement(std::vector<CPoint> vertices)  //C++11
{ 
    m_ElementList.push_back(std::move(vertices));  //move
}

如果编译器不支持 C++11,则按引用传递为:

void AddElement(std::vector<CPoint> const & vertices) //C++03
{ 
    m_ElementList.push_back(vertices);  //copy
}

作为旁注,我认为AddVertices会是一个更好的名字。

您可以将数组称为数组本身或指向第一个元素的指针。例如:

CPoint vertices[11];
// address of the first element
p_vertices = &vertices; 

// allocate
CPoint * vertices = new CPoint[11];
// deallocate
delete [] veritices;

如果你采用后一种方法,你可以简单地将你的向量声明为:

std::vector<CPoint*> m_elementList

并插入为:

void AddElement(CPoint* points) 
{ 
   m_elementList.push_back(points);
}

如果您需要将点数更改为 11 以外的值,这也具有一点优势,因为动态分配允许使用变量代替常量。但是,您需要仔细控制对向量、它包含的数组和元素的访问,以便强制正确使用。

顺便说一句,混合和匹配 STL 和 C 样式指针是完全可以的,特别是如果您希望将数据结构传递很多并且复制元素是不可取或昂贵的。

 std::list<CPoint[11]> m_ElementList;

你声明你的列表类型是错误的,<>括号定义了列表包含什么类型,而不是有多少元素,正确的声明应该是:

std::list<CPoint> m_ElementList;

问题是 CPoint 后面的括号。 模板的目的是提供类的类型(或者更重要的是,类的大小),而不是数量。 尝试:

std::list<CPoint> m_ElementList;