I have three questions based on the following code fragments
I have a list of strings. It just happens to be a vector but could potentially be any source
vector<string> v1_names = boost::assign::list_of("Antigua and Barbuda")( "Brasil")( "Papua New Guinea")( "Togo");
The following is to store lengths of each name
vector<int> name_len;
the following is where I want to store the strings
std::vector<char> v2_names;
estimate memory required to copy names from v1_names
v2_names.reserve( v1_names.size()*20 + 4 );
Question: is this the best way to estimate storage? I fix the max len at 20 that is ok, then add space for null treminator
Now copy the names
for( std::vector<std::string>::size_type i = 0; i < v1_names.size(); ++i)
{
std::string val( v1_names[i] );
name_len.push_back(val.length());
for(std::string::iterator it = val.begin(); it != val.end(); ++it)
{
v2_names.push_back( *it );
}
v2_names.push_back('\0');
}
Question: is this the most efficient way to copy the elements from v1_name to v2_names?
Main Question: How do I iterate over v2_names and print the country names contained in v2_names
To estimate storage, you should probably measure the strings, rather than rely on a hard-coded constant 20. For example:
The main inefficiency in your loop is probably that you take an extra copy of each string in turn:
std::string val( v1_names[i] );could instead beconst std::string &val = v1_names[i];.To append each string, you can use the
insertfunction:This isn’t necessarily the most efficient, since there’s a certain amount of redundant checking of available space in the vector, but it shouldn’t be too bad and it’s simple. An alternative would be to size
v2_namesat the start rather than reserving space, and then copy data (withstd::copy) rather than appending it. But either one of them might be faster, and it shouldn’t make a lot of difference.For the main question, if all you have is
v2_namesand you want to print the strings, you could do something like this:If you also have
name_len:Beware that the type of
name_lenis technically wrong – it’s not guaranteed that you can store a string length in anint. That said, even ifintis smaller thansize_tin a particular implementation, strings that big will still be pretty rare.