std::vector pitfalls, not only for beginners
Bear and Policeman by Jeff Koons. Photo by Amir Kirsh taken at Tel-Aviv Museum of Art

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, that runs on your machine and crashes in production.

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 and careful code review is always required to catch issues like those presented above. But the best way would be to avoid such issues to begin with.

-----?

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 for the 1,000 strings ahead.

Example 3 -- the iterator itr is invalidated once we add items to the vector.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了