c++ - 使用 std::set 替代 BOOST_FOREACH?

标签 c++ boost stl

当您想遍历 std::set 时,什么是 BOOST_FOREACH 的最佳替代方案?

当我尝试执行似乎合理的方法来迭代集合时,我遇到了编译错误。这段代码:

set<string> nameSet;
string aName;
BOOST_FOREACH(nameSet, aName) {
  cout << aName << endl;
}

使用 gcc 4.4.3 生成此编译错误:

error: no match for ‘operator=’ in ‘nameSet = boost::foreach_detail_::deref [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, C = mpl_::bool_<false>](((const boost::foreach_detail_::auto_any_base&)((const boost::foreach_detail_::auto_any_base*)_foreach_cur70)), 0u)’

根据 this link两者不兼容,因为 std::set::iterator 必须允许它引用的值发生变化。

我能想到一些笨手笨脚的方法,但我想知道是否有更简洁的方法来迭代集合。

最佳答案

适合我。也许您将 BOOST_FOREACH 的参数颠倒了。

#include <set>
#include <string>
#include <iostream>
#include <boost/foreach.hpp>

int main(int ac, char **av) {

  std::set<std::string> nameSet(av+1, av+ac);

  BOOST_FOREACH(const std::string& aName, nameSet) {
    std::cout << aName << "\n";
  }

  BOOST_FOREACH(std::string aName, nameSet) {
    std::cout << aName << "\n";
  }

  std::string aName;
  BOOST_FOREACH(aName, nameSet) {
    std::cout << aName << "\n";
  }
}


According to this link the two aren't compatible because std::set::iterator must allow mutation of the value it refers to.

该链接的内容并非如此。你不能做的,以及那个链接说不起作用的,是这样的:

BOOST_FOREACH(std::string& aName, nameSet) {
}

因为你不能从一个常量表达式中形成一个非常量引用。 (即,std::set 的每个 const 成员。)

关于c++ - 使用 std::set 替代 BOOST_FOREACH?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7880380/

相关文章:

c++ - 如何在带有 std::tr1::weak_ptr 的容器上使用 std::remove?

c++ - 我如何在 C++ 中遍历集合?

c++ - 如何从具有 null(0) 字符的 char 数组创建 C++ istringstream?

c++ - boost xml_parser 以格式化空标签

c++ - 将类内的随机数 boost 为静态成员

opencv - Boost multiarray vs OpenCV Mat

c++ - 将指针分配给指针时出现段错误

c++ - 基于证书的登录

c++ - 如果找不到键,则返回一个空的字符串 vector

c++ - 获取类型为 map<classId, set<studentId>> 的两个容器之间差异的最佳方法