问题描述:
创建两个vector,分别给两个容器中输入不同的几个字符串,然后对容器s1中存在而s2中不存在的元素调用函数f1,对s1,s2中都存在的元素调用f2,s2中存在而s1中不存在的调用f3;
代码展示:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void f1(string s)
{
cout << " '" << s << "' " << " is in s1 not in s2, called f1()!" << endl;
}
void f2(string s)
{
cout << " '" << s << "' " << " is in s1 and in s2, called f2()!" << endl;
}
void f3(string s)
{
cout << " '" << s << "' " << " is in s2 not in s1, called f3()!" << endl;
}
void judge(vector<string> &s1, vector<string> &s2)
{
int code = 0;
vector<string>::iterator iter1 = s1.begin();
vector<string>::iterator iter2 = s2.begin();
// in s1 and in s2
// in s1 not in s2
while (iter1 != s1.end())
{
iter2 = s2.begin();
while (iter2 != s2.end())
{
if (*iter1 == *iter2++)
{
f2(*iter1);
//此处跳出是防止s2中已有元素的重复判断,我们希望一旦遇到相同元素后便不再检查
//不能用continue更不能用break
//continue会跳出if,但并没有跳出s2,后续还会重复判断
//break则会跳出最外面的容器s1的遍历,出现没有判断完就已经结束
goto l;
}
else
code++;
}
l:;
if (code == s2.end()- s2.begin())
f1(*iter1);
code = 0;
*iter1++;
}
code = 0;
// in s2 not in s1
iter2 = s2.begin();
while (iter2 != s2.end())
{
iter1 = s1.begin();
while (iter1 != s1.end())
{
if (*iter2 == *iter1++)
{
f2(*iter2);
goto l1;
}
else
code++;
}
l1:;
if (code == s1.end()- s1.begin())
f3(*iter2);
code = 0;
*iter2++;
}
return;
}
int main()
{
vector<string> s1;
vector<string> s2;
string word1, word2;
cout << "enter s1 word (no is end): ";
while (true)
{
cin >> word1;
if (!word1.compare("no"))
break;
s1.push_back(word1);
}
cout << endl << "enter s2 word (no is end): ";
while (true)
{
cin >> word2;
if (!word2.compare("no"))
break;
s2.push_back(word2);
}
cout << endl;
judge(s1, s2);
return 0;
}
代码分析:
在判断模块中代码出现了冗余现象,所以还需想办法引入新函数来解决;
由于每次只是传入的容器不同,为实现函数复用所以我们可以考虑引入模板函数;
判断模块改进代码:
template<typename T>
//判断value是否在list表内,在返回true,不在返回false
bool contains(const vector<T> &list, const T &value)
{
for (auto t : list)
if (t == value)
return true;
return false;
}
void judge(vector<string> &s1, vector<string> &s2)
{
//遍历s1中的每一个元素,与s2一同作为参数传入contains函数进行判断
for (auto _1 : s1)
{
if (contains(s2, _1))
f2(_1);
else
f1(_1);
}
//遍历s2中的每一个元素,与s1一同作为参数传入contains函数进行判断
for (auto _2 : s2)
{
if (contains(s1, _2))
f2(_2);
else
f3(_2);
}
}
使用std::find库函数实现判断模块:
// 使用find函数要引入algorithm库
#include <algorithm>
void judge(vector<string> &s1, vector<string> &s2)
{
vector<string>::iterator iter1 = s1.begin();
vector<string>::iterator iter2 = s2.begin();
vector<string>::iterator p = s1.begin();
vector<string>::iterator q = s2.begin();
iter1 = s1.begin();
while(iter1 != s1.end())
{
p = find(s2.begin(), s2.end(), *iter1);
if (p >= s2.begin() && p < s2.end())
//此处不能使用f2(*p);
//find函数返回的是inputIterator而不是普通的iterator所以不能直接传入
f2(*iter1++);
else
f1(*iter1++);
}
iter2 = s2.begin();
while(iter2 != s2.end())
{
q = find(s1.begin(), s1.end(), *iter2);
if (q >= s1.begin() && q < s1.end())
f2(*iter2++);
else
f3(*iter2++);
}
}