c++中模板函数接收的迭代对象
c++ iterating objects taken in by template function
我有两段看起来很相似的代码,我想利用模板来防止复制代码。
if(!myVector.empty()) {
for(auto& i : myVector)
{
std::cout << i << std::endl;
//some other code that is similar to below
}
}
if(!myUnorederedMap.empty()) {
for(auto i : myUnorderedMap)
{
std::cout << i.second << std::endl;
//some other code that is similar to top
}
}
当我必须在map上调用。second而不是vector时,如何为迭代器编写函数模板?
template <typename T>
T const& getValue(T const& t)
{
return t;
}
template <typename T, typename U>
U const& getValue(std::pair<T, U> const& p)
{
return p.second;
}
template <typename Container>
void foo(Container const& container)
{
if(!container.empty()) {
for(const auto& i : container)
{
std::cout << getValue(i) << std::endl;
}
}
}
虽然,行if(!container.empty())
似乎没有任何用途。你也可以这样写:
template <typename Container>
void foo(Container const& container)
{
for(const auto& i : container)
{
std::cout << getValue(i) << std::endl;
}
}
相关文章:
- 迭代时从向量和内存中删除对象
- 使用迭代器时如何访问对象在向量中的位置?
- std::list 中的迭代器感知对象
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 如何在 Cheerp/js 中迭代动态命名的对象?
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 无法使用迭代器查找类对象。(二进制 '==': 'userInfo' 不定义此运算符)
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 如何创建一个类似"范围"的浮点数可迭代对象?
- 迭代对象向量
- 如何基于可迭代对象进行案例陈述
- 迭代对象列表
- 在C++中迭代对象名称
- 如何迭代对象中的属性
- 任务在删除其中一个迭代对象时会导致段错误
- 为什么迭代对象列表比迭代对象指针列表慢
- 用于 STL 可迭代对象的迭代器循环的宏
- c++中模板函数接收的迭代对象
- c++ /OF每次迭代改变属性的迭代对象