当您想遍历 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/