No doubt some of you have seen my recent posting, all regarding the same program. I keep running into problems with it. To reiterate: still learning, not very advanced, don’t understand pointers very well, not taking a class, don’t understand OOP concepts at all, etc. This code just merges two sorted vectors, farray and sarray, into a single sorted vector. At least, I hope that’s what it does. Tell me:
//int num is to find the size of the original vector and
//build up farray and sarray; not used in the merge process
int num = original.size()
std::vector<int> final;
std::vector<int>::iterator it = farray.begin();
std::vector<int>::iterator iter = sarray.begin();
//farray.size() == (0 thru (num / 2))
//sarray.size() == ((num / 2) thru num)
for (;it != farray.end() && iter != sarray.end();) {
if (*it > *iter) {
final.push_back(*it);
it++;
}
else
{
final.push_back(*iter);
iter++;
}
if (it == farray.end()) {
for (int i = 0; iter < sarray.end(); i++) {
final.push_back(*iter);
}
}
if (iter == sarray.end()) {
for (int i = 0; it < farray.end(); i++) {
final.push_back(*iter);
}
}
}
I rewrote the merge part of my merge sort function so as to…well, make it work. I actually have several questions about this code:
- Is it good form to compare against std::vector::iterators it && iter for my last two if statements if the for loop might change them on its next pass?
- Will the values of iter and it change on this loop’s last pass and screw up my code? Will putting my last if statements before the *it and *iter comparison?
- Does the end() member function refer to the last value of whatever is calling it? It seems like it might extend past it somehow.
EDIT: I will respond to all replies tomorrow, so check back then if you want to hear more. It’s past midnight. G’night.
1 . It’s fine to compare iterators which are from the same container as a for loop condition, but this only makes sense if you are moving one or other iterators in either the increment part if the for loop statement or in the body of the for loop itself. In this for loop you compare
iteragainstsarray.end()but the for loop never changesiter. This means that either there will be no iterations or the for loop will never terminate. Also, you probably want to use!=and not<for the comparison.==and!=work for all iterators,<doesn’t.As
iterstarts where you want the loop to begin, you may want something like this:As you’re still learning (although aren’t we all!), it’s probably instructive to work through an algorithm like this, but you should be aware of
std::mergewhich probably does what you want.(You need to
#include <iterator>and<algorithm>.)2 . I don’t see incrementing iter or it in the outer for loop invalidating the logic in the later for loops, the point in 1. aside.
3 .
end()points to one past the end of a container, so you can use it for loop termination checks, but you shouldn’t try to dereference an iterator which is “==” to “.end()“.