使用泛型函数进行无重复项的复制



我试图使一个通用的功能,将复制元素没有重复从一个块到另一个。函数接受三个指针/三个迭代器,并且必须适用于所有类型的迭代器。函数应该返回一个指针/迭代器,该指针/迭代器正好指向目标块后面的一个位置。

p1和p2属于同一类型。但是,p3不必与p1和p2是同一类型。

#include <iostream>
#include <algorithm>
#include <vector>
template<typename iter_type1, typename iter_type2>
auto CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){
int n=std::distance(p1,p2);
std::unique_copy(p1,p2,p3);
p3+=n;
return p3;
}
int main()
{
std::string s="abc defabcd ghidef",str;
std::vector<int>a{1,1,2,2,3,4,3,5},b;
auto it1=CopyWithoutDuplicate(s.begin(),s.end(),str.begin());
while(it1!=str.begin())
{
std::cout<<*it1;
it1--;
}
std::cout<<endl;
auto it2=CopyWithoutDuplicate(a.begin(),a.end(),b.begin());
while(it2!=b.begin())
{
std::cout<<*it2<<" ";
it2--;
}
return 0;
}

正确的输出应该是:

abc defghi

1 2 3 4 5

我试图使用std::unique_copy为此,但我不知道我在我的代码中犯了什么错误。这不会在屏幕上打印任何东西。

CopyWithoutDuplicate可以简化。

auto CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){
return std::unique_copy(p1,p2,p3);
}

工作示例:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <unordered_set>
template<typename iter_type1, typename iter_type2>
iter_type2 CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){
std::unordered_set<typename std::iterator_traits<iter_type1>::value_type> m;
for (; p1 != p2; ++p1) {
if (m.count(*p1) != 0)
continue;
*p3++ = *p1;
m.insert(*p1);
}
return p3;
}
int main()
{
std::string s="abc defabcd ghidef",str;
std::vector<int>a{1,1,2,2,3,4,3,5},b;
CopyWithoutDuplicate(s.begin(),s.end(),std::back_inserter(str));
for(char c : str)
std::cout<<c;
std::cout<<std::endl;
CopyWithoutDuplicate(a.begin(),a.end(),std::back_inserter(b));
for(int n : b)
std::cout<<n<<" ";
return 0;
}

输出
abc defghi
1 2 3 4 5

最新更新