相关疑难解决方法(0)

是否可以将boost :: foreach与std :: map一起使用?

我发现boost :: foreach非常有用,因为它为我节省了大量的文字.例如,假设我要打印列表中的所有元素:

std::list<int> numbers = { 1, 2, 3, 4 };
for (std::list<int>::iterator i = numbers.begin(); i != numbers.end(); ++i)
   cout << *i << " ";
Run Code Online (Sandbox Code Playgroud)

boost :: foreach使上面的代码变得更加简单:

std::list<int> numbers = { 1, 2, 3, 4 };
BOOST_FOREACH (int i, numbers)
   cout << i << " ";
Run Code Online (Sandbox Code Playgroud)

好多了!然而,我从来没有想过将它用于std::maps 的方法(如果可能的话).该文档仅包含类型为vector或的示例string.

c++ foreach boost

52
推荐指数
2
解决办法
3万
查看次数

Boost.Bind访问std :: for_each中的std :: map元素

我有一个存储带键的简单结构的地图.该struct有两个成员函数,一个是const而另一个不是.我已经使用std :: for_each管理调用const函数而没有任何问题,但是我在调​​用非const函数时遇到了一些问题.

struct MyStruct {
  void someConstFunction() const;
  void someFunction();
};

typedef std::map<int, MyStruct> MyMap;
MyMap theMap;

//call the const member function
std::for_each(theMap.begin(), theMap.end(),
   boost::bind(&MyStruct::someConstFunction, boost::bind(&MyMap::value_type::second, _1)));

//call the non-const member function
std::for_each(theMap.begin(), theMap.end(),
   boost::bind(&MyStruct::someFunction, boost::bind(&MyMap::value_type::second, _1)));
Run Code Online (Sandbox Code Playgroud)

对const成员函数的调用工作正常,但似乎boost内部需要一个const MyStruct,因此在MSVC7.1中出现以下编译错误.

boost\bind\mem_fn_template.hpp(151):错误C2440:'参数':无法从'const MyStruct*__ w64'转换为'MyStruct*const'

我非常感谢有关如何正确设置模板参数的任何帮助,因此bind会正确识别参数并让我调用非const函数.

谢谢,卡尔

c++ foreach boost bind stdmap

8
推荐指数
2
解决办法
7201
查看次数

标签 统计

boost ×2

c++ ×2

foreach ×2

bind ×1

stdmap ×1