如何将数组添加到列表中
How do I add an array to a list?
我有一个名为顶点的数组,它的声明如下:
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;
相关文章:
- 如何在 sqlite3 中的表中添加整数列表
- 有什么方法可以将元素添加到列表中,如图所示?
- 测试驱动开发 c++:如何将对象添加到向量中,将歌曲添加到播放列表并对其进行测试
- 将新元素添加到列表中,并返回对该元素的引用?
- 可视化 如何将 CString 值列表添加到 MFC C++ 中的组合框中?
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- 将集合的随机元素添加到列表中,然后将其从原始集合中移除
- 如何使用LLVM C++API向保留节点列表添加
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- 如何确保我的节点被添加到链接列表中
- 双链接列表添加元素不起作用,不知何故它总是保持为空
- 链接列表添加CPP
- 通过相邻顶点列表添加和减去图形中的边
- 向 C 样式可变参数列表添加额外的参数
- C ++ win 32,我想将项目列表添加到组合框中.我该怎么做
- 如何将QActions列表添加到QMenu并用单个插槽处理它们
- 将一个类的列表添加到另一个类
- 向列表添加项和迭代器问题
- C++向列表添加新的指针对象