c++ - geting index of member of a vector which has been constructed based on the other vector -
let's have std::vector< boost::variant< t1, t2, t3> >, e.g. note in vector obligation have 2 'b' or 1 'q' after 'a'.
note these 'a', 'b' , 'q' different, , not know way mix.
std::vector< boost::variant< t1, t2, t3> > vec; vec = {a, b, b, a, q, a, q, a, b, b, a, q}
thanks boost visitor, i've filtered each element type (t) separately:
veca= {a, a, a, a, a} vecb= {b, b, b, b} vecq= {q, q, q}
now want loop on 'vecq' , each member find index in 'vec' vector , finding index, able find index of 'a' behind 'q' in 'vec' , find index of 'a' in 'veca'.
i know it's spiry question, looking simple way (faster iterating throught vectors).
p.s. using c++98 standard
edit:
the visitor used
template<typename t> struct t_visitor : public boost::static_visitor<> { t_visitor(std::vector<t>& v) : vec(v) {} template<typename u> void operator () (const u&) {} void operator () (const t& value) { vec.push_back(value); } private: std::vector<t>& vec; };
second edit:
in other word: let's have std::vector< boost::variant< t1, t2, t3> >, e.g.
std::vector< boost::variant< t1, t2, t3> > vec; vec = {a1, b15, b1, a5, q0, a5, q1, a9, b7, b6, a4, q2}
note these 'a', 'b' , 'q' different, , not know way mix. thing knowis in vector obligation have 2 'b' *or* 1 'q' after 'a'. when call function know receive vector has been constructed similar vec. have 2 functions gets input "t1, t3" , "t1, t2".
for e.g. gets (a1, b15,b1) or (a5, q0) or (a5, q1) or (a9, b7,b6) or..
but dont know how give them these inputs.
maybe not need split vector different vectors:
auto rngq = boost::adaptors::filter( vec, []( boost::variant<t1, t2, t3> const& v ) { return v.which()==boost::variant<t1, t2, t3>::type<t3>::index; }); // rngq range on type t3
now can iterate on rngq
, calculate vector index:
boost::for_each(rngq, [](boost::variant<t1, t2, t3> const& t3) { // standard guarantees vector elements // put sequential memory ptrdiff_t index = &t3 - &vec[0]; });
if want split elements separate vectors reason, can use same trick long split them separate std::vector< boost::variant<t1,t2,t3>*>
. solution of course requires keep original vector vec
around.
all of not particularly beautiful, judge if there maybe better solution problem.
i don't think there solution if copy elements different vector each. when original vector not sorted, linear search best can do.
Comments
Post a Comment