c++ - conditional iterator over two arrays with STL -


i have 2 arrays. typs int , bool. bool array indicates if element deleted or not. want function returns iterator iterates on not deleted elements. important function should not allocate new memory (like copying element in new vector). there way standard stl?

    std::array<int,5>  element={ 1   , 2   , 4    , 8    , 10   };     std::array<bool,5> deleted={ true, true, false, false, true };     std::vector<int>::iterator getnotdeleted(){              ...     } 

example:

   deleted= { true, true, false, false, true };    element= { 1   , 2   , 4    , 8    , 10   };    getnotdeleted should return std::vector<int>::iterator iterates on     {4,8} 

you can write iterator this, construct iterator knows both vectors, , it's current position in both vectors. then, when advancing iterator, skip elements flagged deleted.

template<class t> struct maybe_deleted_iterator {           typedef int difference_type;     typedef t value_type;     typedef t& reference;     typedef t* pointer;     typedef std::forward_iterator_tag iterator_category;      maybe_deleted_iterator();     maybe_deleted_iterator(std::vector<t>& e, std::vector<bool>& d, bool is_beginning);     maybe_deleted_iterator& operator++();     reference operator*() const;     pointer operator->() const;     bool operator==(const maybe_deleted_iterator& rhs);     bool operator!=(const maybe_deleted_iterator& rhs); private:     std::vector<t>* elements;     std::vector<bool>* deleted;     typename std::vector<t>::iterator e_iter;     std::vector<bool>::iterator d_iter; }; 

then, iterate!

int main() {     std::vector<int>   element = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};     std::vector<bool>  deleted = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1};     maybe_deleted_iterator<int> it(element, deleted, true);     maybe_deleted_iterator<int> end(element, deleted, false);     for(; it!=end; ++it) {         std::cout << *it << ' ';     } } 

http://coliru.stacked-crooked.com/view?id=40e4d1a54f71643ee9f885f82d71fb46-50d9cfc8a1d350e7409e81e87c2653ba

lesnip3r suggested having members begin/end pairs way work on 2 containers, figured easier understand learning. in real code i'd expect see done without mentioning specific container vector.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -