Bla*_*ing 24 c++ for-loop map c++11
是否可以仅使用foreach迭代std :: map中的所有值?
这是我目前的代码:
std::map<float, MyClass*> foo ;
for (map<float, MyClass*>::iterator i = foo.begin() ; i != foo.end() ; i ++ ) {
MyClass *j = i->second ;
j->bar() ;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以做到这一点?
for (MyClass* i : /*magic here?*/) {
i->bar() ;
}
Run Code Online (Sandbox Code Playgroud)
Xeo*_*Xeo 18
Boost.Range的map_values
适配器的神奇之处在于:
#include <boost/range/adaptor/map.hpp>
for(auto&& i : foo | boost::adaptors::map_values){
i->bar();
}
Run Code Online (Sandbox Code Playgroud)
它被官方称为"基于范围的循环",而不是"foreach循环".:)
小智 16
std::map<float, MyClass*> foo;
for (const auto& any : foo) {
MyClass *j = any.second;
j->bar();
}
Run Code Online (Sandbox Code Playgroud)
在c ++ 11(也称为c ++ 0x)中,您可以像在C#和Java中那样执行此操作
Dan*_*ica 16
从C++ 1z/17开始,您可以使用结构化绑定:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> m;
m[1] = "first";
m[2] = "second";
m[3] = "third";
for (const auto & [key, value] : m)
std::cout << value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
由于C ++ 20可以将范围添加适配器std::views::values
从范围库到您的范围为基础的循环。通过这种方式,您可以实现与Xeo's answer 中的解决方案类似的解决方案,但不使用 Boost:
#include <map>
#include <ranges>
std::map<float, MyClass*> foo;
for (auto const &i : foo | std::views::values)
i->bar();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28643 次 |
最近记录: |