I'm working on a program that acts as a very simple voting system which reads numbers from a file, converts the numbers from the file to type unsigned int.
Here is an example of what data in the txt file looks like:
1 34 2 50 23 12
1 30 5 17
5
30 2 3 22
23 45
Each line is a vote from one person and the numbers on each line are the person's candidate preferences, left being first preference, right being last preference.
Once all the data is read from the file, it enters an infinite loop where every round (iteration) it calculates the remaining candidates (i.e. eliminates the candidate with the fewest votes). The program exits with code 0 when a candidate with the majority votes have been found.
My issue is that using the g++ compiler, at around round 40 or so the program starts to slow down and I'm assuming that this is because of a memory leak however I have no idea where in the program it could be leaking.
This is what I get when debugging the program through Deleaker.
Note: Thank you, everyone, for your help. However, as much as I don't want to, I am required to redact the code posted here due to certain reasons. I will not delete the post in case someone can find use in the answers in some way. Hope you understand, thank you.
I am making some guesses here, but in terms of time complexity of the algorithm,
is problematic because
vote_collectionis a vector. SupposeNis that container's size, i.e. the number of votes. Whenp->spent()is true (which happens more likely in later iterations), then you are going to erasep. Erasing an element from a vector has linear time complexity inNin the worst case (when erasing at the beginning, which you are likely to do as you iterate the vector from beginning to end.) Since this will be happening to many of he votes, this loop has quadratic time complexity inN. You always want to try to avoid quadratic complexities if the input variable may be large.The reason for this being the case is that vectors are storing the elements continuously in memory. When you erase an element, all the other elements after the erased one must be shifted one element to close up the gap. This requires moving almost the whole vector when the erased element is close to the beginning.
Instead of using the current approach, you could simply leave all the spent votes in the vector and simply make sure that
ranked_candidatesskips spent votes.