i have list of strings
std::list<std::string> list = { "--version", "--setcolor", "--setint" };
list.push_back("--command1");
list.push_back("--command2");
list.push_back("--command3");
basically list of commands which in the end like to convert them to string
the list, in the end, can contain up to 100 commands.
what is the fastest way to do it in c++17?
UPDATE
It can be also array or other container
the end result should be like this :
std::string s = "--version --setcolor --setint --command1 --command2 --command3";
Thanks
Using std::string
as an accumulator (e.g., "string buffer", as seen in Java or C#) is standard practice in C++ and there's nothing C++11/14/17/20 adds to make it "faster".
Simply add up the length of the substrings - and the delimiters between them - string::reserve
enough capacity in your target string, then string::append
away ...
[@Justin answered in a comment, but putting it here as well because comments are ephemeral]
In C++ strings are modifiable (unlike other languages like Java and C# where they're immutable). So you can change them, including adding characters to them (e.g., via string::append
).
There are two relevant concepts: the string's size - which is how many characters it has right now, and the string's capacity - which is how much it could hold given the storage already allocated to it. If the capacity is the same as the size then adding anything to the string will require a new allocation of storage from the heap, and a copy of the current contents of the string into it (and a deallocation of the old storage back to the heap.) (*) If the capacity is larger than the size then appending new characters will not require that allocation/copy/deallocation if the new characters will fit in the capacity available.
If you're doing multiple appends to a string this might mean multiple alloc/copy/dealloc cycles. Which is expensive.
So instead you reserve additional capacity up front: By calling string::reserve
the capacity is increased to the amount specified in one shot. Then you append all your stuff bit by bit (byte by byte ..., substring by substring) and it'll all fit (if you calculated the necessary capacity correctly) without any additional alloc/copy/dealloc.
string::reserve
is discussed here at cppreference. While you're there check out string::capacity
- to find the current capacity of the string, and why not also look at string::resize
- used to shrink the capacity until it is just as large as needed for the current contents of the string.
(*) Yes I'm leaving out the small string optimization ...