I have a requirement to concatenate multiple small strings into an std::string in an efficient manner.
Let's say there are five strings abc, def, ghi, lmn and pqr. These need to be concatenated thus: /abc/def/ghi/lmn/pqr
The strings would be received in the order opposite to their final positions in the concatenated string: pqr, lmn, ghi, def and abc.
To make this operation efficient, I use the reserve() API of std::string since I know the sizes of all the strings.
Given all this, which of the two is efficient:
Use a stack to store the strings and concatenate them by popping one by one.
Use
insert()API ofstd::stringto move the rest of the string to accommodate the new string at the beginning.
Please note that the number of strings to be concatenated can be up to two thousand.
std::streamfor efficiency, are you in your mind? Why OP needs << ifstd::string::operator +=is sufficient in this case?