I am working on a merge sort function. I got the sort down – I am trying to get my merge part finished. Assume that I am learning C++, have cursory knowledge of pointers, and don’t understand all the rules of std::vector::iterator’s (or std::vector’s, for that matter).
Assume that num is the size of the original std::vector that have copied (std::copy) values from an array of size ‘int ar[num].’ Assume that farray has the values of (0 to (num / 2)) and sarray has the values of ((num / 2) to num).
int num = original.size(); std::vector<int> final(num); for (std::vector<int>::iterator it = farray.begin(); it != farray.end(); ++it) { for (std::vector<int>::iterator iter = sarray.begin(); iter != sarray.end(); ++iter) { if (*it > *iter) final.push_back(*it); else final.push_back(*iter); } }
This code compiles and my latest stable build of Bloodshed Dev-C++ does not throw any warnings or errors. I don’t know if this is valid, I still need to try and cout all the values of final. I just want to know if this is common, prone to errors, or just bad style. And, if so, how you would
It’s valid… but a for loop probably isn’t what you want. When you use two for loops, your inner loop keeps going back to the start every time the outer loop loops. So if your vectors contain:
Then your final array will contain something like:
because you are testing every single combination, and adding the larger one to the final list. A better solution might be to remember an iterator for each list, and just use one loop. Rather than looping over a list, just go through both of them together – if sarray has the larger number, then increment your sarray iterator, and compare that with the old farray iterator. Stop your loop when both sarray and farray are empty.
I haven’t tested it – and if this is for homework, then please try to understand what I’ve done, go away and write it yourself, rather than copy+paste.