Skip to content

Instantly share code, notes, and snippets.

@Grabber
Last active November 13, 2021 17:20
Show Gist options
  • Save Grabber/0356a1125d45a4801326dd8458caf609 to your computer and use it in GitHub Desktop.
Save Grabber/0356a1125d45a4801326dd8458caf609 to your computer and use it in GitHub Desktop.
C++: std::vector reserve
#include <vector>
#include <cstdio>
int main(int argc, char *argv[]) {
std::vector<int> x(10);
std::fprintf(stdout, "x.0: %lu\n", x.size());
x.push_back(1);
x.push_back(2);
x.push_back(3);
std::fprintf(stdout, "x.1: %lu\n", x.size());
for (std::vector<int>::size_type i = 0; i < x.size(); i++) {
std::fprintf(stdout, "x: idx=%lu, val=%d\n", i, x[i]);
}
std::vector<int> y;
std::fprintf(stdout, "y.0: %lu\n", y.size());
y.reserve(10);
y.push_back(1);
y.push_back(2);
y.push_back(3);
std::fprintf(stdout, "y.1: %lu\n", y.size());
for (std::vector<int>::size_type i = 0; i < y.size(); i++) {
std::fprintf(stdout, "y: idx=%lu, val=%d\n", i, y[i]);
}
return 0;
}
@Grabber
Copy link
Author

Grabber commented Nov 12, 2021

The other day I was trying to find and fix a strange bug on a very complex machine learning code I've written years ago. It took me hours and hours to realize that std::vector doesn't have a constructor to pre-allocate n elements of the defined type straight, instead a call to reserved is required.

g++ -std=c++11 vec.cpp -o vec
lvmc@Luizs-MacBook-Pro /tmp % ./vec
x.0: 10
x.1: 13
x: idx=0, val=0
x: idx=1, val=0
x: idx=2, val=0
x: idx=3, val=0
x: idx=4, val=0
x: idx=5, val=0
x: idx=6, val=0
x: idx=7, val=0
x: idx=8, val=0
x: idx=9, val=0
x: idx=10, val=1
x: idx=11, val=2
x: idx=12, val=3
y.0: 0
y.1: 3
y: idx=0, val=1
y: idx=1, val=2
y: idx=2, val=3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment