与&QUOT替换BOOST_FOREACH;纯QUOT; C ++ 11的替代? [英] Replace BOOST_FOREACH with "pure" C++11 alternative?
问题描述
是否有可能与纯C ++ 11等价替换 BOOST_FOREACH
在这个例子吗?
的#include<地图和GT;
的#include<功能>
#包括LT&;升压/ foreach.hpp>
#包括LT&;&iostream的GT;诠释主(){
性病::地图< INT,标准::字符串>地图= {性病:: make_pair(1,1),性病:: make_pair(2,二)};
时int k;
标准::字符串伏;
BOOST_FOREACH(性病::领带(K,V),地图){
性病::法院LT&;< K =&所述;&下; K<< - &所述;&下; V族;&下;的std :: ENDL;
}
}
主要特点是保持在参考文献中的键/值对 K
和 v
。
我试过:
为(的std ::领带(K,V):图)
{
性病::法院LT&;< K =&所述;&下; K<< - &所述;&下; V族;&下;的std :: ENDL;
}
和
自动I =的std ::领带(K,V);
为(ⅰ:地图)
{
性病::法院LT&;< K =&所述;&下; K<< - &所述;&下; V族;&下;的std :: ENDL;
}
但没有的范围为基础的循环理念似乎工作。 presumably的范围为基础的循环需要有前声明:
,因为即使是:
的std ::矢量<&INT GT;测试;
INT I;
为(ⅰ:试验);
是无效的。
我能找到的最接近的是:
为(自动它= map.begin(!);它= map.end()及及(的std ::领带(K,V)= *它,1 ); ++吧)
{
性病::法院LT&;< K =&所述;&下; K<< - &所述;&下; V族;&下;的std :: ENDL;
}
这是不太一样的 BOOST_FOREACH
版本简洁!
有没有一种方法能恩preSS同样的事情,简洁而不在C ++ 11?
提振 为(自动&安培; I:图)
{
的std ::领带(K,V)= I;
//你的code在这里
}
Is it possible to replace the BOOST_FOREACH
in this example with a "pure" C++11 equivalent?
#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;
}
}
The key feature being keeping the key/value pair in the references to k
and v
.
I tried:
for(std::tie(k,v) : map)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
and
auto i = std::tie(k,v);
for(i : map)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
But none of the ranged based for loop ideas seemed to work. Presumably the ranged based for loop is required to have a declaration before the :
, since even:
std::vector<int> test;
int i;
for (i : test);
Isn't valid.
The closest equivalent I can find is:
for (auto it = map.begin(); it!=map.end() && (std::tie(k,v)=*it,1); ++it)
{
std::cout << "k=" << k << " - " << v << std::endl;
}
which isn't quite as succinct as the BOOST_FOREACH
version!
Is there a way to express the same thing succinctly without boost in C++11?
for (auto & i : map)
{
std::tie(k,v) = i;
// your code here
}
这篇关于与&QUOT替换BOOST_FOREACH;纯QUOT; C ++ 11的替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!