コード例 #1
0
//---------------------------------------------------------
// Matlab "intersect" operation
//---------------------------------------------------------
IVec& intersect(const IVec& A, const IVec& B)
{
  // return integer values contained in both 
  // A and B, sorted and without duplicates
  IVec *tmp = new IVec("(A)&(B)", OBJ_temp);

  int Na=A.size(), Nb=B.size(), i=0, val=0, sk=0;
  if (Na<1 || Nb<1) {
    // degenerate case: one array is empty
    tmp->resize(0);
  }
  else
  {
    typedef std::set<int>::iterator SetIt;

    // sort and remove duplicates from A and B by loading into sets
    std::set<int> sA, sB, sC;
    for (i=1; i<=Na; ++i) {sA.insert(A(i));} int lenA = (int) sA.size();
    for (i=1; i<=Nb; ++i) {sB.insert(B(i));} int lenB = (int) sB.size();

    // Use set "C" to store unique values from the 
    // smaller set which also occur in larger set
    SetIt it, it2;
    if (lenA <= lenB) {
      //---------------------------------
      // find values in A that occur in B
      //---------------------------------
      for (it=sA.begin(); it!=sA.end(); it++) {
        val = (*it);
        it2=sB.find(val);
        if (it2 != sB.end()) {
          sC.insert(val);
        }
      }
    } else {
      //---------------------------------
      // find values in B that occur in A
      //---------------------------------
      for (it=sB.begin(); it!=sB.end(); it++) {
        val = (*it);
        it2=sA.find(val);
        if (it2 != sA.end()) {
          sC.insert(val);
        }
      }
    }

    int lenC = (int) sC.size(); tmp->resize(lenC);  
    for (it=sC.begin(), sk=1; it!=sC.end(); it++, sk++) {
      (*tmp)(sk) = (*it);
    }
  }
  if (A.get_mode() == OBJ_temp) { delete (&A); }
  if (B.get_mode() == OBJ_temp) { delete (&B); }
  return (*tmp);
}