Fastest: do nothing. std::string
can basically function as std::vector<char>
for most purposes, and doing literally nothing is always going to be faster than doing something.
std::string p;
cin >> p;
// just use p
// p[0] is the first char, e.g. '0', so you don't have to do anything
// p[1] is the second, etc.
// p.size() is the size
Next fastest: just directly construct your vector:
std::vector<char> data(p.begin(), p.end());
That will make sure to do only one allocation of the correct amount (of at least p.size()
), and will copy the string into the vector as efficiently as feasible.
Next: add each character one at a time:
// C++11
std::vector<char> data;
for (char c : p) {
data.push_back(c);
}
// C++03
for (size_t i = 0; i < data.size(); ++i) {
data.push_back(p[i]);
}
The longer the string, the more extra allocations/copies will be done as opposed to the direct-construction method. The exact amount is implementation dependent, but this approach will always be slower - even your particular implementation default-constructs a vector with large initial capacity (since you would at least have to branch on each push_back
to check if you had to resize
... whereas the direct construction wouldn't even have to do that).