Combing vectors with one or more similar elements in c++ -


good day,

i have logic problem i'm stuck with.

i have vector of vectors contains n number of integers. think of jagged array filled integers.

for example:

vector<vector<int>> myvector 

(lets say, these contents of vector)

myvector[0] = {0,1} myvector[1] = {1,2} myvector[2] = {3,4,5} myvector[3] = {4,5,6} myvector[4] = {7,8} 

what want combine vectors share same element. can see, myvector[0] , myvector[1] share same element value '1', becomes true myvector 2 , 3 since share same element value '4'. myvector[4] stays unchanged since not share values other vectors

my resulting product should this

newvector[0]= {0,1,2} newvector[1]= {3,4,5,6} newvector[2]= {7,8} 

please :)

one obvious , easy way is:

  • pre-sort individual vectors if necessary
  • iterate i through vector<vector<int>>
    • iterator j through i+1..end()
    • use iterators k , l within vectors *i , *j, advancing whichever of *k , *l has lesser value until find shared value or reach end(): if there shared value append *j *i , re-sort, otherwise advance j

that's not optimal solution performance wise, implement/profile , let know if must have faster.


Comments