I have a vector of pair of vectors(V1,V2) called pairV1V2 of the following form:
(1,2,3),(938,462,4837) -> (V1,V2)
(3,9,13),(938,0472,944)
(81,84,93),(938,84,845)
Then I need to retain the following:
(1,2,3),(938,462,4837) -> (V1,V2)
(3,9,13),(938,0472,944)
(81,84,93),(84,845)
I need to start scanning pairV1V2 from the beginning and where ever any two V1's are not equal, there I need to delete the intersecting elements from V2. I wrote the following code for doing same. However, my code turns out to be very inefficient as my vector pairV1V2 is big and it has many elements in V2 (about a billion).
int main(int argc, char** argv) {
std::vector<std::pair<std::vector<unsigned>, std::vector<unsigned> > > pairV1V2;
std::vector<std::pair <std::vector<unsigned>,std::vector<unsigned> > >::iterator itm2,lm2=pairV1V2.end();
for(std::vector<std::pair <std::vector<unsigned>,std::vector<unsigned> > >::iterator itm=pairV1V2.begin(), lm=pairV1V2.end(); itm!=lm; ++itm)
{
//Outer values
vector<unsigned> outerV1=(*itm).first;
vector<unsigned> outerV2=(*itm).second;
sort(outerV2.begin(), outerV2.end());
itm2=itm;
itm2++;
for(itm2;itm2!=lm2;++itm2)
{
vector<unsigned> innerV1=(*itm2).first;
vector<unsigned> innerV2=(*itm2).second;
vector<unsigned> setDiffV1;
std::set_difference(innerV1.begin(), innerV1.end(), outerV1.begin(), outerV1.end(),
std::inserter(setDiffV1, setDiffV1.end()));
if(setDiffV1.size()==0) //check whether any two V1's are different
{
sort(innerV2.begin(), innerV2.end());
if((itm->second.size()!=0)&&(itm2->second.size()!=0)){
std::vector<unsigned> delIntersectingElem;
std::set_intersection(outerV2.begin(),outerV2.end(),innerV2.begin(), innerV2.end(),
std::back_inserter(delIntersectingElem));
if(delIntersectingElem.size()!=0) //if there are intersecting V2's
{
for(std::vector<unsigned>::iterator its=(itm2->second).begin(),ls=(itm2->second).end();its!=ls;)
{
//if *its is present in delIntersectingElem then delete it.
if(!(std::find(delIntersectingElem.begin(), delIntersectingElem.end(), (*its)) == delIntersectingElem.end()))
{
(itm2->second).erase(its); //delete intersecting elements from inner v2
ls--;
}else{
++its;
}
}
}
}
}
}
}
return 0;
}
Can someone please help me in improving my present code -- it gives the correct answer (In the example I might have missed a few case for brevity-- but the code handles all of them) but is extremely slow (as diagonalised by perf). I'll be grateful if improvements are suggestion in my present piece of code. However, if the logic of the two codes are same, then a new algorithm is also acceptable
Aucun commentaire:
Enregistrer un commentaire