C++ deque iterate to second last element -
i trying iterate through deque excluding last entry. ideally avoid counting , comparing length, tried
auto it_end = dq.rbegin(); it_end++; ( auto = dq.begin(); !=it_end; ) { if ( cond() ) { = dq.erase( ); } else { it++; } }
but compiler complains there no match operand seems understandable since have reverse iterator , regular iterator. there elegant way stop before last element avoids counting? like, offset? tried usign back, turned out reference not iterator, != not happy either.
you can use dq.end() - 1
1 before end.
you can use std::remove
or std::remove_if
remove items want instead of doing job on own. note kind of partitioning operation--it returns iterator, , want keep beginning of range iterator. want delete after iterator, end of range provided input.
in case, might on general order:
std::deque<int> vals { 1, 2, 3, 4, 5, 6, 7, 8}; // iterator 1 before end of `vals` auto end = vals.end()-1; // remove items in range (so except `8`) auto pos = std::remove_if(vals.begin(), end, [](int v){ return v %2 == 0;} ); // erase items "removed" vals.erase(pos, end); // show result (v : vals) std::cout << v << ", ";
Comments
Post a Comment