class SList // list of strings
{
struct SNode // store string
{
string item;
SNode *next;
SNode(const string &s, SNode *n) : item(s), next(n) { }
} *front;
public:
class iterator
{
SNode *current;
public:
iterator(SNode *start) : current(start) { }
SNode* operator++() // prefix version!
{
return current = current->next;
}
SNode* operator++(int) // postfix version
{
SNode* tmp = current;
current = current->next;
return tmp;
}
string& operator*() // de-reference (since no parameters)
{
return current->item;
}
bool operator==(const iterator &other)
{
return current == other.current;
}
bool operator!=(const iterator &other)
{
return current != other.current;
}
}; // end of iterator
iterator begin()
{
return iterator(front);
}
iterator end()
{
return iterator(nullptr);
}
... other List operations to add/remove items ...
};
list<double> nums;
...
double sum = 0.0;
for(auto it = nums.begin(); it != nums.end(); ++it)
sum += *it;
list<string> todo;
...
// find first "go to class", of amu
list<string>::iterator pos = todo.begin();
// better:
auto pos = todo.begin();
while ( pos != todo.end() && *pos != "go to class" )
++pos;
if ( pos != todo.end() )
cout << "Found it.";
int empty_count = 0;
for(auto const & item : todo) // access element without copy
if ( item.empty() )
++empty_count;
for(auto item : todo) // copies each string
cout << item << endl;
for(auto& item : todo) // can modify element value
item = "take a break";
std::list<int> l = {3,-1,10};
std::sort(l.begin(), l.end()); // not legal: cannot index a linked list; should use merge sort
//Typical compiler diagnostic without concepts:
// invalid operands to binary expression ('std::_List_iterator<int>' and
// 'std::_List_iterator<int>')
// std::__lg(__last - __first) * 2);
// ~~~~~~ ^ ~~~~~~~
// ... 50 lines of output ...
//
//Typical compiler diagnostic with concepts:
// error: cannot call std::sort with std::_List_iterator<int>
// note: concept RandomAccessIterator<std::_List_iterator<int>> was not satisfied
float x = ...;
int y = (int)x; // truncate
int *zs = (int*)malloc(100 * sizeof(int)); // legal, but not recommended
A *x = new B; // assume B derived from A
... ((B*)x)->b_method() ... // call a method from class B
static_cast<int>(x) -
more explicit than the () notation
const, but you know you can call it without
changing the object's state