我正在嘗試制作一個通用函式,它將沒有重復的元素從一個塊復制到另一個塊。函式接受三個指標/迭代器,并且必須適用于所有型別的迭代器。函式應該回傳一個指標/迭代器,它正好指向目標塊后面的一個位置。
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;
}
正確的輸出是:
美國廣播公司
1 2 3 4 5
我嘗試使用std::unique_copy它,但我不知道我在代碼中哪里出錯了。這不會在螢屏上列印任何內容。
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470411.html
