C ++ Iterator Composition

I will try to save the sample code very simply, but it may have errors as I type it in place.

I have a class called Phone.

class Phone
{
 public:
  Phone(std::string manufacturer, std::string model, std::vector<Feature> features);

 private:
  std::vector<Features> features;
  std::string model;
  std::string manufacturer;
};

I have a structure called Feature.

struct Feature
{
   Feature(std::string feature, std::string category);
   std::string feature;
   std::string category;
};

As you can see, the phone has a list (vector) of functions: i.e. Bluetooth, GPS, radio, etc., which have a category: network, navigation, multimedia.

Now information about phones and features is stored in the sqlite3 database. I have a helper function that will retrieve a specific phone model from the database and return a populated phone object. I also have a function that takes a Phone object and writes the Phone to the database.

, . , . -, , .

Phone

std::vector<Feature>::iterator begin()
std::vector<Feature>::iterator end()

, - , , .

http://accu.org/index.php/journals/1527, "memberspaces", . , , , .

, , , , .

.

+3
2

:

typedef std::vector<Feature> Features;

Features::iterator features_begin();
Features::iterator features_end();
Features::const_iterator features_begin() const;
Features::const_iterator features_end() const;

:
1)

 // Note: you'll need to define an operator<< for Feature
 // can be used with std::algorithms
 std::copy( phone.features_begin(), phone.features_end(),
   std::ostream_iterator<Feature>( std::cout, "\n\r" ) );     

2)

// Note: shamelessly borrowed from http://www.boost.org/doc/libs/1_44_0/doc/html/foreach/extensibility.html
// add overloads of range_begin() and range_end() for Phone::Features
inline Phone::Features::iterator range_begin( Phone& phone ){
   return phone.features_begin();
}

inline Phone::Features::iterator range_end( Phone& phone ){
   return phone.features_end();
}

namespace boost{
   // specialize range_mutable_iterator and range_const_iterator in namespace boost
   template<>
   struct range_mutable_iterator< Phone >{
      typedef Phone::Features::iterator type;
   };

   template<>
   struct range_const_iterator< Phone >{
      typedef Phone::Features::const_iterator type;
   };
}
...
// can be used with BOOST_FOREACH
BOOST_FOREACH( Feature x, phone ){
   std::cout << x << std::endl;
}

P.S. Jonannes , boost::range, features_xxx() xxx_features() ( , ).

+1

BOOST_FOREACH,

const std::vector<Feature>& getFeatures() const;

?

+1

Source: https://habr.com/ru/post/1763191/


All Articles