Reply to comment

Pass By Iterator

Pass by iterator is not a new concept, but one that we are going to perhaps give a new name to today and propose as a standard for normal usage.

If you take for example the normal way of passing around standard containers:

// Print a vector of strings separated by spaces.
void print(const std::vector<std::string> &t_vector)
{
  for(std::vector<std::string>::const_iterator itr = t_vector.begin();
        itr != t_vector.end();
        ++itr)
  {
    std::cout << *itr << " ";
  }       
}
 
std::vector<std::string> m_vec;
m_vec.push_back("Hello");
m_vec.push_back("World");
print(m_vec);

The idea of "Pass By Iterator" that we are proposing involves never again writing code like the above.

With this example if you wanted to change your container to an std::list<std::string> or an std::set<std::vector> you would have to modify several lines of code in the print() function.

If, however, you had passed a range of iterators to print in the first place your code would be reusable, more succinct and, most importantly, more open to refactoring.

//Print a range of iterators separated by spaces.
template<typename InItr>
void print(InItr begin, InItr end)
{
  while (begin != end)
  {
    std::cout << *begin << " ";
    ++begin;
  }
}
 
std::vector<std::string> m_vec;
m_vec.push_back("Hello");
m_vec.push_back("World");
print(m_vec.begin(), m_vec.end());

This technique can be used everywhere you pass containers around in your code. One downside is that it will probably be more difficult to debug your compilation errors.

The concept of passing around containers as a pair of iterators is how the standard library was designed. One way to think about it is that you are adding to your own personal library of algorithms.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.