2

编辑:我放弃了!我现在只是简单地使用for (string& word : sentence) { .. }BOOST_FOREACH是绝望的。谢谢你。

我读过这个这个,他们根本没有帮助。特别是我想问第二个链接。为什么必须在命名空间下定义一些奇怪的结构boost?我想要启用 BOOST_FOREACH 的类是在我自己的命名空间中定义的。如果我在 中定义我的迭代器,我如何访问该类的数据namespace boost { .. }?这是没有意义的。我不知道为什么IEnumerable在 C++ 中找到 的等价物花了我这么多时间!不boost应该节省我的时间吗?

谁能告诉我迭代这个类的最巧妙的方法:

class Sentence {
private:
    vector<string> words;
}

使用此代码:

Sentence sentence;
BOOST_FOREACH(string word, sentence) {
    // ..
}

谢谢。

4

1 回答 1

3

根据文档,任何看起来像标准库容器的东西都可以工作。最简单的方法是在您的类中公开一对迭代器。如果您不想实现自己的,只需使用vector<string>迭代器:

class Sentence 
{
public:
  typedef vector<string>::iterator iterator;
  typedef vector<string>::const_iterator const_iterator;
  const_iterator begin() const { return words.begin(); }
  const_iterator end() const { return words.end(); }
private:
    vector<string> words;
};

编辑它似乎BOOST_FOREACH不够聪明,无法理解标准库类容器类型,但它可以理解一对标准库迭代器。所以需要一个额外的步骤:

#include <iostream>
#include <utility>
int main()
{
  Sentence sentence;
  auto s = std::make_pair(sentence.begin(), sentence.end());
  BOOST_FOREACH(std::string word, s) {
    std::cout << word << std::endl;
  }
}

注意 1:您可能希望使用类型擦除来解耦迭代器的显式类型,但这可以看作是一种改进。有关更多信息,请参阅此相关讨论

注 2:我从来都不是BOOST_FOREACH. 基于 C++11 范围的循环使我更不可能在实际代码中使用它。

于 2013-12-26T05:29:17.567 回答