查找在A集合但不在B集合中的元素

// find.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <vector>
#include <string>
#include <map>
#pragma warning(disable:4786)
#include <iostream>

using namespace std;

std::vector<std::string> VecA, VecB;

void creatVector(string str, std::vector<std::string>& vectorObj)
{
 vectorObj.push_back(str);
}

void findInAButB(std::vector<std::string> VecA,
     std::vector<std::string> VecB,
     std::vector<std::string>& resultVect)
{
 if ( !(VecA.size() > 0) || !(VecB.size() > 0))
 {
  return;
 }

 std::vector<std::string>::const_iterator itA, itB;
 for (itA = VecA.begin(); itA != VecA.end(); itA++)
 {
  for (itB = VecB.begin(); itB != VecB.end(); itB++)
  {
   if (!(*itA).compare(*itB))
   {
    break;
   }
  }
//   if (VecB.end() != itB)
//   {
//    continue;
//   }
//   else //
  if ( VecB.end() == itB)
  {
   resultVect.push_back(*itA);
  }
 }
}

int _tmain(int argc, _TCHAR* argv[])
{
 VecA.clear();
 cout<<"请输入VecA,以空格回车结束:"<<endl;
 for (;;)
 {
  string str;
  getline(cin, str);
  if (str.empty())
  {
   cout<<"VecA输入结束."<<endl;
   break;
  }
  creatVector(str,VecA);
 }

 VecB.clear();
 cout<<"请输入VecB,以空格回车结束:"<<endl;
 while(1)
 {
  string str;
  getline(cin, str);
  if (str.empty())
  {
   cout<<"VecB输入结束."<<endl;
   break;
  }
  creatVector(str,VecB);
 }

 cout<<"下面查出在VecA中但不在VecB的元素集."<<endl;
 std::vector<std::string> resultVectA;
 findInAButB(VecA, VecB, resultVectA);
 std::vector<std::string>::const_iterator itorR;
 cout<<"输出查找到的结果"<<endl;
 for (itorR = resultVectA.begin(); itorR != resultVectA.end(); itorR++)
 {
  cout<< *itorR <<endl;
 }

 cout<<endl<<"下面查出在VecB中但不在VecA的元素集."<<endl;
 std::vector<std::string> resultVectB;
 findInAButB(VecB, VecA, resultVectB);
 std::vector<std::string>::const_iterator itorB;
 cout<<"输出查找到的结果"<<endl;
 for (itorB = resultVectB.begin(); itorB != resultVectB.end(); itorB++)
 {
  cout<< *itorB <<endl;
 }

 system("PAUSE");
 return 0;
}


版权声明:本文为zhujun012原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。