How to loop over elements in a std::set/ add condition to std::for_each over a std::set in vs2008?

StackOverflow https://stackoverflow.com/questions/16799459

  •  30-05-2022
  •  | 
  •  

Domanda

from here : 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)));
  }

I want to call the deliver method on all members of set except the participant passed to this function, how to do this in vs2008?

È stato utile?

Soluzione 3

A simple for loop using an iterator should do the trick.

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

Altri suggerimenti

for (auto &p : participants_)
    if (p != participant)
    {
        //do your stuff
    }

Really, the clearest thing might just be to write a for loop directly:

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

or the C++03 equivalent:

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

I don't think using for_each buys you any generality or expressiveness here, mostly because you're not composing anything you might want to re-use.


If you do find yourself wanting to do something similar regularly, you could write a generic for_each_not_of. Is that really the case?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top