So I have the following method:
template <class DT> //needs testing
DT& LinkedSortedArrays<DT>::find (const DT& key)
{
list<SortedArray<DT>>::iterator it = SAList.begin();
for( ; it != SAList.end(); ++it){
try{
if (it == SAList.begin() && key < (*it)[0]) throw Exception();
return (*it).find(const_cast<DT&> (key));
} catch (ArrayException e) {
}
}
throw Exception();
}
I have previously defined the classes Exception and ArrayException. (*it).find(const_cast<DT&> (key)) will throw a ArrayException everytime that key is not found in the specific Array class being searched at the moment. SAList is a STL List. The code compiles just fine. However I haven’t tried it in my program. Why? I need somebody to confirm or correct me on the following assumptions I have done:
- Whenever
if (it == SAList.begin() && key < (*it)[0]) throw Exception();throws an exception, it means it will throw it outside the for loop and even outside the method, right? - I am almost sure that the last line
throw Exception();will throw the Exception outside the method. - The way the for loop is arranged, it won’t skip the first element of SAList, right? I mean, I have seen this specific code all over the internet that serves to iterate through all elements of the list as if it was standard or flawless, but… that
++itis twisting my brain. Help? - I was receiving an error of
can't convert const int to int&(since thefind()in(*it).find(const_cast<DT&> (key))is not the one belonging toLinkedSortedArraysbut rather a different one that requires a DT& variable andLinkedSortedArrays‘sfind()has parameters of type const DT&) and I found that a possible solution might be writing it asconst_cast<DT&> (key). I need a second opinion on this.
Lastly, I understand if this is not a specific question and therefore I get downvotes and/or the question gets closed. I simply don’t really know where else to ask.
If it is the case that I am asking in the wrong place. My apologies.
Yes, it will go up the stack until it finds the appropriate
catchhandler. If it finds no such handler, the program will terminate.Yes it will.
No, it will not, since
endshould return an iterator to one past the end, not the last element. Unless that container is badly designed as well, but you’ll have to consult the documentation to be sure.That’s a bad design,
findshould take its parameter byconstreference. Since you can’t, you’ll have to make a copy unless you want to risk undefined behaviour: