将迭代器传递给模板
Passing iterators to templates
本文关键字:迭代器 更新时间:2023-10-16
很抱歉这个问题不清楚。我需要使用以下模板使用插入算法对属于自定义类的对象数组进行排序:
template<typename pointer, typename T, typename Functype>
void sort_array(pointer puntatore, T* obj, int dim, Functype pred){
T val;
for(int i=1; i<dim; i++){
val=obj[i];
for(int j=(i-1); j>=0; j--){
if(pred(obj[j].*puntatore, val.*puntatore)){
obj[j+1]=obj[j];
obj[j]=val;
}
}
}
}
我想知道如何编写一个更通用的模板,该模板可以接受指向类 T
对象的任何类型的迭代器,而不仅仅是指针。在参数列表中写入T obj
会给我在赋值中的变量T val
带来麻烦,在这种情况下,这就像*val=obj[i]
val
本身是一个迭代器。有没有办法告诉模板他必须接受指向类 T
对象的通用迭代器(即以相同的方式编写T*
告诉它期望指向类 T
对象的指针)?
我如何使用此模板的示例
class Example{
int first;
int second;
};
template<typename pointer, typename T, typename Functype>
void sort_array(pointer puntatore, T* obj, int dim, Functype pred){
T val;
for(int i=1; i<dim; i++){
val=obj[i];
for(int j=(i-1); j>=0; j--){
if(pred(obj[j].*puntatore, val.*puntatore)){
obj[j+1]=obj[j];
obj[j]=val;
}
}
}
}
int main(){
Example array[5]={{1,2},{2,4},{1,7},{5,3},{6,7}};
//now i sort the elements in the array by their first element in a decreasing order
sort_array(&Example::first, array, 5, [](int a, int b){return (a<b);});
}
好吧,
你可以从 STL 实现中汲取灵感,提供一个接口,该接口将采用一个范围而不是如下所示的数组:
template<typename BidirectionalIterator, typename Predicate =
std::less<typename std::iterator_traits<BidirectionalIterator>::value_type>>
void
insertion_sort(BidirectionalIterator first, BidirectionalIterator last,
Predicate pred = {}) {
if(first != last) {
auto it = first;
while(++it != last) {
auto it2 = it;
while(it2 != first) {
auto it3 = it2;
--it3;
if(pred(*it2, *it3)) {
std::swap(*it2, *it3);
} else {
break;
}
--it2;
}
}
}
}
现场演示
但请注意,您还可以为对象提供重载operator<
或operator>
,以便与标准谓词一起使用:
bool
operator<(T const &A, T const &B) {
return A.*puntatore < B.*puntatore;
}
bool
operator>(T const &A, T const &B) {
return A.*puntatore < B.*puntatore;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?