Reputation: 4680
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:
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?throw Exception();
will throw the Exception outside the method.++it
is twisting my brain. Help?can't convert const int to int&
(since the find()
in (*it).find(const_cast<DT&> (key))
is not the one belonging to LinkedSortedArrays
but rather a different one that requires a DT& variable and LinkedSortedArrays
's find()
has parameters of type const DT&) and I found that a possible solution might be writing it as const_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.
Upvotes: 0
Views: 145
Reputation: 75150
Yes, it will go up the stack until it finds the appropriate catch
handler. If it finds no such handler, the program will terminate.
Yes it will.
No, it will not, since end
should 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, find
should take its parameter by const
reference. Since you can't, you'll have to make a copy unless you want to risk undefined behaviour:
DT nonconstkey = key;
return it->find(nonconstkey);
Upvotes: 2