C++ String Interview Question

后端 未结 7 1202
悲哀的现实
悲哀的现实 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 18:56

    // compiled with cl /Ox first_last_n.cpp /W4 /EHsc
    
    inline void
    first_last_n2(string::size_type n, const std::string &s, string &out)  // method 2
    {
      // check against degenerate input
      assert(n > 0);
      assert(n <= s.size());
    
      out.reserve(2*n);
      out.assign(s, 0, n);
      out.append(s, s.size()-n, n);
    }
    

    Times:

    method 1:  // original method
    2.281
    method 2:  // my method
    0.687
    method 3:  // your code.
    0.782
    

    Note: Timing specifically tests "long" strings. I.e. those where short string optimization is not used. (My strings were 100 length).

提交回复
热议问题