![](/img/trans.png)
[英]Difference between BOOST_FOREACH and c++11 for range based loop?
[英]Replace BOOST_FOREACH with “pure” C++11 alternative?
是否可以用“純”C ++ 11等效替換此示例中的BOOST_FOREACH
?
#include <map>
#include <functional>
#include <boost/foreach.hpp>
#include <iostream>
int main() {
std::map<int, std::string> map = {std::make_pair(1,"one"), std::make_pair(2,"two")};
int k;
std::string v;
BOOST_FOREACH(std::tie(k, v), map) {
std::cout << "k=" << k << " - " << v << std::endl;
}
}
關鍵特性是將鍵/值對保持在對k
和v
的引用中。
我試過了:
for(std::tie(k,v) : map)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
和
auto i = std::tie(k,v);
for(i : map)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
但是基於for循環的想法似乎都不起作用。 據推測,基於范圍的for循環需要在:
之前有一個聲明,因為偶數:
std::vector<int> test;
int i;
for (i : test);
無效。
我能找到的最接近的等價物是:
for (auto it = map.begin(); it!=map.end() && (std::tie(k,v)=*it,1); ++it)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
這不像BOOST_FOREACH
版本那么簡潔!
有沒有辦法在C ++ 11中沒有提升的情況下簡潔地表達同樣的事情?
for (auto & i : map)
{
std::tie(k,v) = i;
// your code here
}
這將產生與Boost宏相同的輸出
for( auto const& k : map ) {
std::cout << "k = " << k.first << " - " << k.second << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.