Home > other >  Sort merge vector of vectors
Sort merge vector of vectors

Time:12-06

I have a vector of vectors, like this vector<vector<string>> vecData;

for example, a vector contains the following data(the data inside the vectors has already been sorted):

vecData[0] == {"1","5"}
vecData[1] == {"2","7"}
vecData[2] == {"6","9"}
vecData[3] == {"4"}`

how can I get a sorted merged vector resVec

recVec[0] == "1" 
recVec[1] == "2" 
recVec[2] == "4" 
..............
recVec[6] == "9"` 

I tried something like this, but I understand that this is complete nonsense

vector<vector<string>> separateFileData;
............................
vector<string> temp = separateFileData[0];
temp.reserve(1024);
for (auto iter = separateFileData.begin(); iter<separateFileData.end() - 1; iter  )
{
    merge(iter->begin(), iter->end(), (iter 1)->begin(), (iter   1)->end(), temp.begin());
}

CodePudding user response:

Like this, assuming I'm understanding you right.

vector<string> recVec;
for (const auto& v : vecData)
     recVec.insert(recVec.end(), v.begin(), v.end());
sort(recVec.begin(), recVec.end());

All strings from vecData are combined into recVec which is then sorted.

  •  Tags:  
  • c
  • Related