std::vector pitfalls, not only for beginners
The default container in C++ is std::vector. It's not me saying that, it is the spec itself:
When choosing a container, remember vector is best; leave a comment to explain if you choose from the rest!?
But if you think using a vector is a piece of cake, well in a way it is but it isn't. Like anything in C++, it has its sharp edges. From using it inefficiently to actually writing buggy code
This is for example a piece of code that you can find in actual code base:
std::vector<std::string> strs(10);
for(size_t i=0; i<strs.size(); ++i) {
strs[i] = std::to_string(i);
}
I would leave it for the reader to find the problem with above code.
Here is another example:
std::vector<std::string> strs;
for(size_t i=0; i<1000; ++i) {
strs.push_back(std::to_string(i));
}
Again, something is not done right.
The following code presents an example in which the user needs to remember a position in a vector, but something is not done right:
领英推荐
std::vector<std::string> strs;
// ... vector is populated
auto itr = find_if(strs.begin(), strs.end(), [](const auto& s){s[0] == 'A'});
strs.push_back("a string");
// do something with itr here
Yes, we may see the issues. But at the same time we might miss them. Static code analysis
-----?
To read more about std::vector pitfalls to avoid, follow to my article posted at medium.
-----?
Problems in the code snippets above:
Example 1 -- we create 10 empty strings then we just override them with new strings. We should reserve capacity for 10 strings, not initialize size! Then we should use push_back.
Example 2 -- we add 1,000 strings into a vector, probably making the vector to resize itself several times. We should reserve capacity
Example 3 -- the iterator itr is invalidated once we add items