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
// 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).