I’m trying to make a vector that holds pointers to each of the first strings in a vector of vector of strings. I’m going to be passing first_words_in_subvecs to the \bin\sort program to sort/print them. I figured it’s a waste of cpu time/space to make a new vector of actual strings, since I’m just going to be passing them anyway. Am I right in thinking it will be faster to just make pointers to the strings I want to send? And why doesn’t this code work? I don’t get any warnings or errors, but it seg faults when I run it.
int print_sorted_subvectors(vector< vector<string> > &sorted_subsets_vec)
{
vector<string*> first_words_in_subvecs;
for(int i = 0; i < sorted_subsets_vec.size(); i++)
{
first_words_in_subvecs[i] = &sorted_subsets_vec[i][0];
}
}
There’s probably no need to store pointers to strings in a vector. The
std::stringclass is pretty efficient, using techniques such as copy-on-write to avoid unnecessary copies of actual string data. You’ll probably have no efficiency problem iffirst_words_in_subvecsis a regularvector<string>(and your code will be easier to understand and more reliable, too).It’s hard to say why your current code is segfaulting. Are you certain that every sub-vector of
sorted_subsets_vecis nonempty?