一、实际例子
#include<iostream>
#include<string>
#include<vector>
struct Vertex
{
float x, y, z;
};
std::ostream& operator<<(std::ostream& stream, const Vertex& vertex)
{
stream << vertex.x << "," << vertex.y << "," << vertex.z;
return stream;
}
void Function(const std::vector<Vertex>& vertices)//在函数中传递数组一般需要&,因为要确保不是将整个数组都复制到其中
{
}
int main()
{
std::vector<Vertex> vertices;//动态数组
vertices.push_back({ 1,2,3 });//加入元素
vertices.push_back({ 4,5,6 });
Function(vertices);
for (int i = 0; i < vertices.size(); i++)//遍历动态数组
std::cout << vertices[i] << std::endl;
for (Vertex v : vertices)//遍历动态数组的另外一种形式,这实际上是将每个vertex复制到这个for循环当中,我们一般不想这样做
std::cout << v << std::endl;
for (Vertex& v : vertices)//加上&就不会把东西复制过来
std::cout << v << std::endl;
vertices.clear();//清除动态数组
vertices.erase(vertices.begin() + 1);//清除第二个元素
std::cin.get();
}
注:Vector本身就很慢