CSE2305 - Object-Oriented Software Engineering
Week 11

Topic 22: The C++ Standard Library


Synopsis


Reinventing the wheel


The "wheels" of C++


The Standard Library¤ - A box of wheels


The string class¤


String example:

#include <string>

using namespace std;
// AND LATER...

string s0;
string s1 = "cat";
string s2 = "alogue";

cout << s1 << s2 << endl;

s0 = s1 + s2;

int at = s0.find("log");

cout << s0.substr(at,3,5) << endl;

s1.replace(2,1,"nary");

char c = s2[4];

s2[4] = 'q';


The sequence container class¤¤ templates


Deque example

#include <deque>
using namespace std;

// AND LATER...

deque<string> names;

names.push_back("Shiranthi");
names.push_back("James");
names.push_back("Emily");
names.push_back("Damian");

names[2] = "Jesse";

for (int i=0; i<names.size(); i++)
{
	cout << names.at(i) << endl; // will throw exception if no element at i
}

//  or a better way to print elements
copy( names.begin(); names.end(); ostream_iterator<string>(cout,"\n")); // prints all elements separated by newlines


The associative container classes¤¤


Map example

#include <map>
using namespace std;

// AND LATER

map<string,int>       mark_for;

mark_for["Damian"] = 100;
while (markfile >> name >> mark)
{
	mark_for[name] = mark;
}
while (cin >> name)
{
	cout << name << " scored " << mark_for[name] << endl;
}


The iostream classes¤


The complex class¤ template


Complex example

#include <complex>
using namespace std;

// AND LATER....

complex<double> minus1 (-1,0);
complex<double> i      (0,1);
complex<double> pi     (3.141592654,0);

complex<double> sqrtminus1 = sqrt(minus1);

if (i !=  sqrtminus1)
{
	cout << "Warning: local anomoly in spacetime!" << endl;
	cout << "Checking fundamental constants:" << endl;
	cout << exp(pi*i)-1 << " (should be 0)" << endl;
}


Iterators¤


Iterator example 1

#include <deque>
using namespace std;

// AND LATER...

deque<string> names;

names.push_back("Shiranthi");
names.push_back("James");
names.push_back("Emily");
names.push_back("Damian");

names[2] = "Jesse";

deque<string>::iterator next = names.begin();
deque<string>::iterator last = names.end();

for (; next != last; next++)
{
	cout << next->length() << endl;
}


Iterator example 2

#include <vector>
#include <algorithm>
using namespace std;

// AND LATER...

vector<double> heights = load_heights();

// TALL HEIGHTS

for (vector<double>::iterator next = heights.begin();
     next != heights.end();
     next++)
{
	if (*next > 2.00)
	{
		cout << (*next) << endl;
	}
}

// SHORTEST 10 HEIGHTS

sort(heights.begin(),heights.end());

vector<double>::iterator from = heights.begin();
vector<double>::iterator to = from+10;

for(;from != to && from != heights.end(); from++)
{
	cout << (*from) << endl;
}


Other components


Reading


This material is part of the CSE2305 - Object-Oriented Software Engineering course.
Copyright © Jon McCormack & Damian Conway, 1998–2005. All rights reserved.