You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm learning C++ and like to use your github to check my work/improve. Overall it is very well done and thank you for sharing!
The issue in your bin_lst() function is that it will not check against the exactly middle or exactly last element in a container.
So if you have a list{1,2,3,4,5,6,7,8,9,10}; , the function will not find 5 or 10. If you add the following code, it should work better. Your bin_lst() function will also work directly with vector as well.
I'm new to Github, so sorry if my formatting is subpar. If you add :
if (half == 0 && *(--last) == val)
return last;
just after the loop at line 60, it will fix your code. It's the best I can manage, so I'm not sure if there's a better solution.
`template<typename Iter, typename T>
Iter bin_lst(Iter first, Iter last, const T& val)
{
auto half = std::distance(first, last);
auto end = last;
while (first != last && half != 0) {
if (*first == val) return first;
half /= 2;
auto mid = first;
std::advance(mid, half);
*mid > val
? std::advance(last, -half)
: std::advance(first, half);
}
//loop exits when half = 0
//but last value wasn't checked
if (half == 0 && *(--last) == val)
return last;
return end;
}`
The text was updated successfully, but these errors were encountered:
I'm learning C++ and like to use your github to check my work/improve. Overall it is very well done and thank you for sharing!
The issue in your bin_lst() function is that it will not check against the exactly middle or exactly last element in a container.
So if you have a list{1,2,3,4,5,6,7,8,9,10}; , the function will not find 5 or 10. If you add the following code, it should work better. Your bin_lst() function will also work directly with vector as well.
I'm new to Github, so sorry if my formatting is subpar. If you add :
just after the loop at line 60, it will fix your code. It's the best I can manage, so I'm not sure if there's a better solution.
`template<typename Iter, typename T>
Iter bin_lst(Iter first, Iter last, const T& val)
{
auto half = std::distance(first, last);
auto end = last;
//loop exits when half = 0
//but last value wasn't checked
if (half == 0 && *(--last) == val)
return last;
}`
The text was updated successfully, but these errors were encountered: