Skip to content

Instantly share code, notes, and snippets.

@Broxzier
Last active April 24, 2018 15:01
Show Gist options
  • Save Broxzier/c609de199a421ece580d3f52ff0b7216 to your computer and use it in GitHub Desktop.
Save Broxzier/c609de199a421ece580d3f52ff0b7216 to your computer and use it in GitHub Desktop.
Vector of Vectors vs List of Vectors
// Vector of vectors
{
// Initialize vector of vectors
std::vector<std::vector<int>> vov;
vov.resize(1);
vov.back() = { 1, 2, 3, 4 };
// Get reference to first list - used as argument for the threads
auto& ref = vov.back();
// Add a load of containers to make it reallocate
for (int i = 0; i < 200; i++)
vov.push_back(std::vector<int>{ i, i + 1, i + 2, 1000 });
// Error! `ref` is invalid - the container has been moved
printf("ref = { %d, %d, %d, %d }\n", ref[0], ref[1], ref[2], ref[3]);
}
// List of vectors
{
// Initialize list of vectors
std::list<std::vector<int>> lov;
lov.resize(1);
lov.back() = { 1, 2, 3, 4 };
// Get reference to first list - used as argument for the threads
auto& ref = lov.back();
// Add a load of containers to make it reallocate
for (int i = 0; i < 200; i++)
lov.push_back(std::vector<int>{ i, i + 1, i + 2, 1000 });
// Everything is fine, ref is still refering to the same container which has not been moved
printf("ref = { %d, %d, %d, %d }\n", ref[0], ref[1], ref[2], ref[3]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment