使用模板化复合类型推理实现unique_copy
Implementing unique_copy with templated comp type inference
我已经实现了我的unique_copy
版本并且它可以工作。问题是我必须这样称呼它:
my_unique_copy(
in.begin(), // ok
in.end(), // ok
out.begin(), // ok
equals<Container::iterator> // <--sucks
);
我不喜欢的是 equals 函数equals<Container::iterator>
它必须用 Container::iterator
显式实例化。我认为该类型可以从in.begin()
推断出来,该类型属于Container::iterator
类型。我试图在函数原型中将equals
声明为bool()(Iterator,Iterator)
,但它失败了。
../untitled2/main.cpp:20:32: error: 'parameter' declared as function returning a function
bool()(Iterator,Iterator) equals){
^
../untitled2/main.cpp:20:34: error: expected ')' before 'equals'
bool()(Iterator,Iterator) equals){
^
../untitled2/main.cpp:20:34: error: expected initializer before 'equals'
../untitled2/main.cpp: In function 'int main()':
../untitled2/main.cpp:41:79: error: 'my_unique_copy' was not declared in this scope
my_unique_copy(in.begin(),in.end(),out.begin(),equals<Container::iterator>);
^
这是代码:
template <typename Iterator>
bool equals(Iterator fst, Iterator snd){
return *fst==*snd;
}
bool myfunction (int i, int j) {
return (i==j);
}
template <typename Iterator, typename Comparator>
void my_unique_copy(Iterator begin,
Iterator end,
Iterator out_begin,
Comparator equals){
if (begin==end){
return;
}
*out_begin=*begin;
++begin;
while (begin!=end){
if (!equals(out_begin, begin)){
*(++out_begin)=*begin;
}
++begin;
}
}
int main(){
using Container = vector<int>;
Container in{1,2,2,3};
Container out(4);
my_unique_copy(in.begin(),in.end(),out.begin(),equals<Container::iterator>);
for_each(out.begin(), out.end(), [](int v){cout<<v<<" ";});
cout<<endl;
unique_copy(in.begin(),in.end(),out.begin(),myfunction);
for_each(out.begin(), out.end(), [](int v){cout<<v<<" ";});
}
这就是我想要的:
my_unique_copy(in.begin(), in.end(), out.begin(), equals);
如果你把
equals
实现为函子而不是函数模板,你基本上可以得到你想要的:
struct equals {
template<typename Iterator>
bool operator ()(Iterator fst, Iterator snd) const {
return *fst == *snd;
}
};
// ...
my_unique_copy(in.begin(), in.end(), out.begin(), equals{});
请注意,由于标准库已经有一个equal_to
函子,因此您可能应该选择一个不同的名称,以更好地表示函子和std::equal_to
之间的区别,例如 iter_equals
.或者,更好的是,您应该只使用 std::equal_to
而不是通过取消引用调用的迭代器来重新发明轮子equals
而不是传入迭代器本身(这就是标准库算法所做的)。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 使用模板化复合类型推理实现unique_copy