C++ 在stl映射和列表上迭代的通用循环(c+;+;)
是否有任何方法可以编写一个泛型循环,其中cih迭代say stl map(关联容器)和list(非关联容器)的值C++ 在stl映射和列表上迭代的通用循环(c+;+;),c++,templates,stl,C++,Templates,Stl,是否有任何方法可以编写一个泛型循环,其中cih迭代say stl map(关联容器)和list(非关联容器)的值 模板 空富(T&T) { 对于(自动iter=t.begin();iter!=t.end();++iter) { printf(“%d\n”,*iter);//将适用于std::list,但不适用于std::map } } 感谢使其适用于std::map-使用boost中的正确选项: foo(someMap | boost::adaptors::map_values); 你也可以
模板
空富(T&T)
{
对于(自动iter=t.begin();iter!=t.end();++iter)
{
printf(“%d\n”,*iter);//将适用于std::list,但不适用于std::map
}
}
感谢使其适用于std::map-使用boost中的正确选项:
foo(someMap | boost::adaptors::map_values);
你也可以用Eric Niebler的
如果你不能使用提升/范围-使用一些特性:
template <typename ValueType>
struct ValueGetter
{
static Value& get(ValueType& value)
{
return value;
}
};
template <typename Key, typename Value>
struct ValueGetter<std::pair<const Key, Value>>
{
using ValueType = std::pair<const Key, Value>;
static Value& get(ValueType& value)
{
return value.second;
}
};
template <typename ValueType>
auto& getValue(ValueType& value)
{
return ValueGetter<Value>::get(value);
}
template<typename T>
void foo(T &t)
{
for (auto iter = t.begin(); iter != t.end(); ++iter)
{
printf("%d\n", getValue(*iter));
}
}
模板
结构参数获取程序
{
静态值和获取(值类型和值)
{
返回值;
}
};
模板
结构参数获取程序
{
使用ValueType=std::pair;
静态值和获取(值类型和值)
{
返回值。秒;
}
};
模板
自动和获取值(值类型和值)
{
返回ValueGetter::get(值);
}
模板
空富(T&T)
{
对于(自动iter=t.begin();iter!=t.end();++iter)
{
printf(“%d\n”,getValue(*iter));
}
}
实际上,已经有std::for_each(#include
)用于这些目的。您可以使用适当的处理程序(例如。G以lambda的形式:
std::vector<int> v;
std::map<int, double> m;
std::for_each(v.begin(), v.end(), [](auto i) { printf("%d\n", i); });
std::for_each(m.begin(), m.end(), [](auto const& i) { printf("%d %f\n", i.first, i.second); });
std::vector v;
std::map m;
std::for_each(v.begin(),v.end(),[](自动i){printf(“%d\n”,i);});
std::for_each(m.begin(),m.end(),[](auto const&i){printf(“%d%f\n”,i.first,i.second);});
我确实喜欢它的显示方式,在大多数情况下,这将是我最喜欢的选择
让我的评论更加清晰,填补空白。作者的循环张贴在这里是好的。在本例中,唯一有问题的是printf()
。为了解决这个问题,我建议使用重载stream operator()之类的方法来打印std::map
ostream& operator<<(ostream& os, pair<string, int> it){
os << it.first << " => " << it.second;
}
除了printf()。在这里,还可以使用基于范围的循环
template<typename T>
void foo(T &t){
for(auto it : t)
cout << it << endl;
}
模板
空富(T&T){
用于(自动it:t)
它们可能是两个不同的容器。我想你需要专门化你的函数模板。可能你需要重新考虑/放弃这种方法。已经有了一个。你有一个通用循环应该可以工作,唯一的事情是printf()我建议使用C++中的CUT,并将流操作符重载到屏幕上打印内容。它们有不同的语义。如果是一个映射,你想从<代码> *ITER <代码>中得到什么?你想实现什么?@ RoTEM通用循环,删除任何集合中的指针,例如,你映射Adth.在Eric Niebler的标准下,将在C++标准中添加范围。@ Jayes是的-我知道-我希望它将在C++ 17中。我会的。
ostream& operator<<(ostream& os, pair<string, int> it){
os << it.first << " => " << it.second;
}
template<typename T>
void foo(T &t){
for(auto it=t.begin(); it=t.end(); ++it){
cout << *it << endl;
}
}
template<typename T>
void foo(T &t){
for(auto it : t)
cout << it << endl;
}