0

ここから: 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)));
  }

この関数に渡された参加者を除く set のすべてのメンバーで配信メソッドを呼び出したいのですが、vs2008 でこれを行うにはどうすればよいですか?

4

3 に答える 3

2
for (auto &p : participants_)
    if (p != participant)
    {
        //do your stuff
    }
于 2013-05-28T19:07:45.733 に答える
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。本当にそうですか?

于 2013-05-28T19:07:58.740 に答える
1

イテレータを使用した単純な for ループでうまくいくはずです。

std::set<chat_participant_ptr>::iterator iter;
for(iter = participants_.begin();iter != participants_.end();++iter)
{
    if(participant != iter)
    {
        call deliver function on *iter 
    }
}
于 2013-05-28T19:11:14.333 に答える