Last active
November 13, 2021 17:20
-
-
Save Grabber/0356a1125d45a4801326dd8458caf609 to your computer and use it in GitHub Desktop.
C++: std::vector reserve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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::vectordoesn't have a constructor to pre-allocatenelements of the defined type straight, instead a call toreservedis required.