CS253

CS253: Software Development with C++

Spring 2017

Begin And End

See this page as a slide show

Begin And End

Half-open interval

.begin() and .end()

vector<int> v = {11, 22, 33, 44, 55};
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
11 22 33 44 55 

or:

vector<int> v = {11, 22, 33, 44, 55};
for (auto it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
11 22 33 44 55 

++it is probably faster than it++.

const

Why does this fail?

const vector<int> v = {11, 22, 33, 44, 55};
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
c.cc:2: error: conversion from '__normal_iterator<const int*,[...]>' to 
   non-scalar type '__normal_iterator<int*,[...]>' requested

const

Solution #1

One solution—use the correct type:

const vector<int> v = {11, 22, 33, 44, 55};
for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
11 22 33 44 55 

Solution #2

A better solution—let auto figure it out:

const vector<int> v = {11, 22, 33, 44, 55};
for (auto it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
11 22 33 44 55 

Solution #3

The best solution—avoid all of this:

const vector<int> v = {11, 22, 33, 44, 55};
for (auto val : v)
    cout << val << ' ';
11 22 33 44 55 

.cbegin() and .cend()

.rbegin() and .rend()


vector<int> v = {11, 22, 33, 44, 55};
for (auto it = v.crbegin(); it != v.crend(); ++it)
    cout << *it << ' ';
55 44 33 22 11 

Don’t get too excited

Modified: 2017-04-06T20:34

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building