使用迭代器执行对象操作的函数
Function using iterators to perform a object operation
假设我有一个std::array<SomeType, N>
,我想调用一个函数,该函数使用迭代器来处理std::array
中的对象,但不知道容器是std::array
。
SomeType 是一个具有公共成员函数 doSomething() 的类
例如,函数可能是:
template<typename Iterator>
void action(Iterator &beg, Iterator &end) {
for (; beg != end; ++beg)
beg->doSomething();
}
可以通过以下方式调用此函数:
int main() {
std::array<SomeType, 10> a;
action<std::array<SomeType, 10>::iterator>(a.begin(), a.end());
}
但我想知道这是否是这样做的方法?特别是因为模板可以用于每个类。有没有办法在不让函数知道容器是std::array
的情况下将函数限制为SomeType
?
-
修复代码:不应要求左值参数。事实上,迭代器旨在有效地复制。
template<typename Iterator> void action(Iterator beg, Iterator end) // ^^^^^^^^^^^^ ^^^^^^^^^^^^
-
让模板参数推导完成它的工作:
action(a.begin(), a.end());
请注意,标准库已经有许多算法涵盖了"在某个容器中的某个范围内做同样的事情"的一般情况:
#include <array>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
struct SomeType
{
void doSomething();
SomeType mutatedCopy() const;
int someValue() const;
};
int add_value(int i, const SomeType& st) {
return i + st.someValue();
}
void call_something(SomeType& st) { st.doSomething(); }
auto mutate_copy(SomeType const& st) { return st.mutatedCopy(); }
int main() {
std::array<SomeType, 10> a;
std::vector<SomeType> b;
std::for_each(a.begin(), a.end(), call_something);
std::for_each(b.begin(), b.end(), call_something);
std::transform(a.begin(), a.end(), a.begin(), mutate_copy);
std::transform(b.begin(), b.end(), b.begin(), mutate_copy);
auto tot = std::accumulate(a.begin(), a.end(), 0, add_value)
+ std::accumulate(b.begin(), b.end(), 0, add_value);
// you can even transform into dissimilar containers:
std::transform(a.begin(), a.end(), std::back_inserter(b), mutate_copy);
}
相关文章:
- 我可以在 C++ 中的函数体之外进行操作吗?
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- 无法调用成员函数,尝试正确执行此操作仍然失败
- 不执行任何操作的函数调用C++
- 如何实现对序列对进行操作的C++元函数
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 在函数中操作 std::array
- 避免通过操作从私有构造函数间接实例化
- 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建平凡可构造的对象?
- 如何检测函数是否执行IO操作
- 如何将操作委托给函数返回
- 在MySql中使用字符串操作函数有什么问题
- Rcpp 中"List"的操作函数 - 类似于 R 中的"Reduce function"
- 无操作函数模板
- 按位操作函数
- 当人们想操作函数中的指针时,为什么要传入双指针
- 如何在c++中操作函数以根据条件输出不同的结果
- 使用std::map时必须互斥的所有操作/函数是什么?