Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A a pointer to a pointer is a perfectly valid C idiom. I'd say typedef'ing a pointer would raise more eyebrows :)

E.g. I have a singly-linked list of

    struct x { int y; struct x* next };
I want to locate an element here and then maybe remove it (1), maybe insert a new one before (2) or after (3), maybe replace (4), or maybe just return what I've found (5). How do I write this base locator function? If I do it naively and return just a pointer to struct x I can only do (3) and (5); but if I return a pointer to a pointer, I can do all five.

A doubly-linked list is simpler in this regard because the element has pointers to both neighbors and thus a mere pointer to struct x would suffice, but it's also one pointer more expensive. By the way, will your C++ code work with singly-linked lists?

Also, look: your C++ example calls four methods. The C code calls only one (malloc), all the rest is core language. It's 4:1 ratio for extra complexity.



> By the way, will your C++ code work with singly-linked lists?

Yes, but you'll use merge instead:

    list.merge(std::forward_list<T>{val});
I chose to use std::lower_bound for binary search. If you are content with linear search like in the C example, you can even write a single function that works for both doubly linked lists and singly linked lists.

> Also, look: your C++ example calls four methods. The C code calls only one (malloc), all the rest is core language. It's 4:1 ratio for extra complexity.

This is what I call unnecessary manual inlining and reinventing the wheel for no good reason.


Binary search on a list??




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: