InRainbows's blog

By InRainbows, history, 18 months ago, In English

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

  • Vote: I like it
  • +54
  • Vote: I do not like it

»
18 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by InRainbows (previous revision, new revision, compare).

»
18 months ago, hide # |
 
Vote: I like it +17 Vote: I do not like it

You can use ssize() always to get the signed size of something. Then you'll never have to worry about the first issue.

»
18 months ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

Also some pragmas could cause WA in your solution.

»
18 months ago, hide # |
 
Vote: I like it +3 Vote: I do not like it
»
18 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by InRainbows (previous revision, new revision, compare).