My results show that the strtok() version works about twice as fast as the character-by-character version.
In any case, what do you mean by 'exceeding the time limit'?
His function misses the first character in the string. It works by looking at each character in turn. If it is not the '/', then the character is copied to the end of a temporary string, else the temporary string is added to the end of the input vector. That excessive use of
push_back() is probably killing his time...
Your function is better written -- it uses the standard library the way it is supposed to be used and makes no errors in processing. You did forget to
delete[] cstr;
before the end of your function though (that's a memory leak).
I would have used a
stringstream to parse the line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector <string> name( string s )
{
vector <string> result;
istringstream iss( s );
string token;
while (getline( iss, token, '/' ))
result.push_back( token );
return result;
}
|
I really don't like
strtok(), but I am really impressed that you took care to use it properly (considering the fact that it modifies the input string). My function runs slower than yours though...
The thing to remember is that the difference in times is really insignificant... I had to do it 10,000 times each to calculate useful results.
Hope this helps.