C++ String Interview Question

后端 未结 7 1238
悲哀的现实
悲哀的现实 2021-02-13 18:22

I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised

7条回答
  •  你的背包
    2021-02-13 19:17

    If you must pass the tests then you're going to have to write inefficient code, because you must return a copy of a string. This implies you must use dynamic allocation, possibly multiple times because of the copy.

    So change the tests and change the signature.

    template
    Out first_last_n(const std::string::size_type& n, const std::string& s, Out r)
    {
        r = copy_n(s.begin(), n, r);
        std::string::const_iterator pos(s.end());
        std::advance(pos, -n);
        return copy_n(pos, n, r);
    }
    

    Then call it like so:

    std::string s("Hello world!");
    char r[5];
    r[4] = 0;
    first_last_n(2, s, r);
    

    This allows you to use dynamic programming, and it eliminates the need of dynamic allocation in the function.

    I like my algorithms minimalistic, and I purposely eliminated the check for n being smaller or equal to the size of the string. I replace the check with a pre-condition for the function. Preconditions are faster than checks: they have zero overhead.

提交回复
热议问题