Hello everyone! Today I want to write about common C++ mistakes that may seem correct while writing code, but are actually wrong upon deeper inspection. There are only few right now because finding one requires deep experience in coding and often quite specific to certain problems. If you have any suggestions, I can add them to this blog.
1. size_t type is unsigned
When you get the size of some container it returns unsigned integer, not regular integer. It may lead to mistakes like this:
for (int i = 0; i < Ar.size() - 3; i++)
If size of Ar is less than 3, Ar.size() - 3 won't be some negative integer, it will be large positive integer because of how unsigned integers work. You can just turn it to integer using (int)t.size() or ssize(t) (proposed by glowbigger).
2. Common mistake with pointers
Let's say you wanted to create a vector of multiple pointers, and you wrote it like this:
vector<node*> T(N, new node());
This might seem correct but it isn't. Keep in mind that all those pointers will point into one node, not N nodes, so if you change one, it will affect all of them. Instead, you have to add them one by one:
vector<node*> T;
for (int i = 0; i < N; i++) T.push_back(new node());
3. Pragmas may cause WA's (proposed by feev1x)
Remember to add pragmas only when your code is getting TLE, as a possible optimization. But keep in mind it might make your code work incorrectly.
Useful blogs with the same goal:
Some bugs and features looks weird but really exists by OtterZ







