majo majo - 1 month ago 16
C++ Question

What is the recommended way to flatten a std::vector<CString> to a multi_sz using C++ / STL

I want to write a list of strings (ATL::CString) stored in a std::vector to a REG_MULTI_SZ value in the Windows registry. I know how to do this in plain C (iterate once to get the total length, allocate a buffer, copy the strings to the buffer separated by "\0").

Know I tried the following using STL (sorry that I have to use VS2010 with "for each"):

std::vector<TCHAR> multiline_sz;
for each ( CString entry in myStringList )
{
TCHAR* buf = entry.GetBuffer();
multiline_sz.insert(multiline_sz.end(), &buf[0], &buf[entry.GetLength()]);
multiline_sz.push_back(L'\0');
}
multiline_sz.push_back(L'\0');


This works, but I wonder if there is a more elegant or faster way using STL.

Answer

CString::GetBuffer() is already zero-terminated, so it's valid to do

for each ( CString entry in myStringList )
{
   TCHAR const* buf = entry.GetBuffer();
   multiline_sz.insert(multiline_sz.end(), &buf[0], &buf[entry.GetLength()+1]);
}