According to what I heard std::vector stores data contiguously and when you try to add or delete an element to it grow or shrink by allocating new memory and copies everything from the old memory to the new memory with the changes and deletes the old memory
in the code below I have a copy constructor it says copied every time the class gets copied it gave me 6 copied messages when I had 3 elements and that was fine but when I added another element it gave me 7 messages
Isn't it supposed to give me 10? And how to optimize that?
#include <iostream>
#include <vector>
struct Vertex
{
int x, y, z;
Vertex(int x, int y, int z) : x(x), y(y), z(z)
{
}
Vertex(const Vertex &vetrex) : x(vetrex.x), y(vetrex.y), z(vetrex.z)
{
std::cout << "Copied" << std::endl;
}
};
int main()
{
std::vector<Vertex> vertices;
vertices.push_back({1, 2, 3});
vertices.push_back({4, 5, 6});
vertices.push_back({7, 8, 9});
vertices.push_back({10, 11, 12});
}
Aucun commentaire:
Enregistrer un commentaire