Skip to content

Instantly share code, notes, and snippets.

@jackbergus
Last active August 29, 2015 13:57
Show Gist options
  • Save jackbergus/9387426 to your computer and use it in GitHub Desktop.
Save jackbergus/9387426 to your computer and use it in GitHub Desktop.
A simple example of how to use iterators in C++11
/*
* iteratortest.cpp
* This file is part of iteratortest.cpp
*
* Copyright (C) 2014 - Giacomo Bergami
*
* iteratortest.cpp is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* iteratortest.cpp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with iteratortest.cpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <vector>
using namespace std;
struct elem {
int value;
};
typedef vector<struct elem> Vector;
//This adapter increments the Vector::const_iterator, and returns only the field named `value`
//in order to hide the whiole `struct elem`
class Iter
{
public:
Iter (Vector::const_iterator begin)
: start( begin )
{ }
bool operator!= (const Iter& other) const {
return start != other.start;
}
int operator* () const {
return start->value;
}
const Iter& operator++ () {
++start;
return *this;
}
private:
Vector::const_iterator start;
};
// The object over which you should iterate, should provide a begin and an end method, that return two adapters named Iter
class VectorIterable
{
public:
VectorIterable (Vector vec) : v{vec} {}
Iter begin () const {
return Iter(v.begin());
}
Iter end () const {
return Iter(v.end());
}
private:
Vector v;
};
// sample usage of VectorIterable as an interface to get only the field named `value` in the iteration
int main()
{
struct elem a, b, c;
a.value = c.value = 1;
b.value = 2;
Vector vec;
vec.push_back(a);
vec.push_back(b);
vec.push_back(c);
for (int i: VectorIterable(vec)) {
std::cout << i << std::endl;
}
// Output:
// 1
// 2
// 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment