Replace BOOST_FOREACH with “pure” C++11 alternative?

吃可爱长大的小学妹 提交于 2019-12-05 12:51:02

问题


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?


回答1:


for (auto & i : map)
{
    std::tie(k,v) = i;
    // your code here
}



回答2:


This produces the same output as the Boost macro

for( auto const& k : map ) {
  std::cout << "k = " << k.first << " - " << k.second << std::endl;
}



回答3:


With C++17 this can now be done using structured bindings, for instance:

#include <map>
#include <string>
#include <iostream>

int main() {
  const std::map<std::string, std::string> map = {std::make_pair("hello", "world")};
  for (auto& [k,v]: map) {
    std::cout << "k=" << k << ", v=" << v << "\n";
  }
}

This is certainly what I'd choose to do in newer projects.



来源:https://stackoverflow.com/questions/10523648/replace-boost-foreach-with-pure-c11-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!