Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 21 Exercise 7 Fix #24

Open
ghost opened this issue Jun 16, 2021 · 0 comments
Open

Chapter 21 Exercise 7 Fix #24

ghost opened this issue Jun 16, 2021 · 0 comments

Comments

@ghost
Copy link

ghost commented Jun 16, 2021

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;

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants