简体   繁体   中英

filter a vector of boost variant into a new vector?

I am looking for the best way to filter a vector of the boost variant which has been defined like this:

 boost::variant<T1*, T2, T3> Var;
 std::vector<Var> Vec;

when I call this vector, what is the best way to filter only T2 bounded type and insert into new vector? or in other way, I want something like this

std::vector<T2> T2Vec = ...(how to filter it from Vec)....

thank you!

EDIT: Since using a "visitor" is more robust, I'm also wondering of anyone could give me a solution using "visitor"?

thanks again!

The simplest solution would be to loop over Vec , checking if the element is a double , then push the double into a T2Vec . This is a C++03 version:

for (std::vector<Var>::const_iterator it = Vec.begin(); it != Vec.end(); ++it)
{
  if (it->which() == 1) T2Vec.push_back(boost::get<T2>(*it));
}

C++11 version:

for (const auto& v : Vec)
{
  if (v.which() == 1) T2Vec.push_back(boost::get<T2>(v));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM