r/learnprogramming • u/Temporary-Warthog250 • Apr 05 '22
Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them
Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.
Someone else who reads yours and does understand it, try to explain it to them to help them learn
1.6k
Upvotes
1
u/ShelZuuz Apr 06 '22
I did. That's called a deque (in C++ at least), but in the sole exception of a queue that needs double-ended insertion, the benefits of a deque does not generally outweigh the drawbacks. But either way, in that one scenario a deque definitely has a place - I'll grant you that.
However, you started by saying: "If you have no way of knowing the size in advance you have a problem". That's not actually a problem when just comparing a list to a vector.
Adding an unknown number items to the end of a list vs. a vector, inserting into the vector is going to keep doubling the size of the vector when it gets full and then copy over all of the elements to the new allocation. That is still order of magnitudes faster than inserting into the end of a list. And once you're done inserting, you can copy the vector to another vector that's the exact right size you want. With all that, the whole process will still be 10 times faster than inserting into the end of a list, and at no time in between will the vector (or two times the size of the vector if you include the temporary to make a copy), take up more space than the list.
The only consistent advantage a list has over a vector is double-ended insert/delete. (But the deque is better at it again).
However, when you look at code from juniors in a codebase, you'll see std::list all over the place rather than std::vector because they just learned the basics of it in Computer Science class with O-theory behind it and they think that inserting into a list actually is faster or takes less space than inserting into a vector. They're not doing it because they are writing queues that need actual double ended insertion.
I mean lists has to be taught because it forms the basis of binary trees, but I wish after that people will forget about them and stop attacking my codebase with std::list all over in critical perf paths that I have to go fix years later.
Speaking of binary trees... they're also only better if you have a binary tree that's very often being written to after initial construction. If you have a binary tree that's predominantly read from, you're again better off inserting into a vector, doing a sort afterwards and searching it with standard binary search. My ultimate pet peeve is when people get already ordered data from SQL inside a vector, and then go store it into a binary tree for cached access. Like ... duuude.