【问题标题】:How to loop over elements in a std::set/ add condition to std::for_each over a std::set in vs2008?如何在vs2008中的std::set上循环std::set中的元素/向std::for_each添加条件?
【发布时间】:2013-05-28 19:00:30
【问题描述】:

从这里: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/chat/chat_server.cpp

  std::set<chat_participant_ptr> participants_;
  ....
  participants_.insert(participant);
  ....

 void deliver(const chat_message& msg, chat_participant_ptr participant)
  {
    recent_msgs_.push_back(msg);
    while (recent_msgs_.size() > max_recent_msgs)
      recent_msgs_.pop_front();

    // I want to call the deliver method on all members of set except the participant passed to this function, how to do this?
    std::for_each(participants_.begin(), participants_.end(),
        boost::bind(&chat_participant::deliver, _1, boost::ref(msg)));
  }

我想在集合的所有成员上调用传递方法,除了参与者传递给这个函数,在vs2008中如何做到这一点?

【问题讨论】:

    标签: c++ boost stl stdset


    【解决方案1】:
    for (auto &p : participants_)
        if (p != participant)
        {
            //do your stuff
        }
    

    【讨论】:

      【解决方案2】:

      真的,最清楚的可能就是直接写一个for循环:

      for (auto &p : participants_) {
          if (p != participant)
              p->deliver();
      }
      

      或等效的 C++03:

      for (std::set<chat_participant_ptr>::iterator i = participants_.begin();
           i != participants_.end(); ++i)
      {
          if ((*i) != participant)
              (*i)->deliver();
      }
      

      我不认为在这里使用for_each 会给你带来任何普遍性或表现力,主要是因为你没有编写任何你可能想要重复使用的东西。


      如果你确实发现自己想要定期做类似的事情,你可以写一个通用的for_each_not_of。真的是这样吗?

      【讨论】:

      • 我在自动时缺少类型说明符
      • 你是用 C++11 编译的吗?如果不是(并且如果您无法启用它),这只是编写一个常规的 for 循环迭代集合的一种紧凑方式。
      • 就像我说的,要么 开始使用 C++11,要么 在集合上编写一个常规循环。你想让我说明一下吗?
      【解决方案3】:

      使用迭代器的简单 for 循环应该可以解决问题。

      std::set<chat_participant_ptr>::iterator iter;
      for(iter = participants_.begin();iter != participants_.end();++iter)
      {
          if(participant != iter)
          {
              call deliver function on *iter 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-29
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 2023-03-12
        • 1970-01-01
        相关资源
        最近更新 更多