通过模板访问 std 容器的迭代器
Access to iterators of std containers by a template
我想编写一个函数,该函数以 std 容器开头和结尾将容器中的所有值添加到第三个参数中。例如,如果我有
std::vector<int> my_ints{ 1, 2, 3 };
int sum_int = accumulate(my_ints.cbegin(), my_ints.cend(), 10); //should return 16.
我想以一种可以与任何 std 容器一起使用的方式概括这个函数。如何编写可以访问元素迭代器的模板?
template<typename It, typename T>
T accumulate(It begin, It end, T x)
{
for (It i = begin; i != end; ++i)
{
x = x + i;
}
return x;
}
这就是我目前所拥有的。但是,它不编译,因为 x 和 i 不是同一类型。
你应该使用 std::for_each 来做到这一点,而不是编写自己的函数。它将接受任何容器和任何范围的值。
如果你想编写你自己的 for range 语句:
template <typename C>
auto accumulate(const C& c) {
typename C::value_type x { };
for (auto value : c) {
x += value;
}
return x;
}
std::vector<int> my_ints{ 1, 2, 3 };
int sum = accumulate(my_ints);
正如彼得在评论中提到的,您正在尝试将实际的迭代器添加到x
而不是它指向的值。您需要取消引用迭代器才能获取值:
template<typename It, typename T>
T accumulate(It begin, It end, T x) {
// there's no need create a new iterator (i) here, use the one you already have (begin):
for(; begin != end; ++begin)
x += *begin; // use * to dereference the iterator
return x;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何在c++迭代器类型中包装std::chrono
- std::vector::迭代器是否可以合法地作为指针
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- 修改 std::vector 会使迭代器无效吗?
- std::list 中的迭代器感知对象
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 为什么范围算法与 std 的迭代器不兼容?
- 从 std::vector 迭代器中执行函数指针
- 无法获得等效的 std::less 来用于嵌套迭代器
- 再次获得 std::map 会更改之前的迭代器
- 为什么"std::uninitialized_copy"通常取消对未初始化内存的迭代器的引用不是未定
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- 比较未引用的映射迭代器(std::pairs):C2678
- STL迭代器std::distance()错误
- ->秒是否为迭代器 std::map::end()?