C++ crash course Class 3 designing C++ programs, classes, control structures Types • Last time: basic types and variables • Today: – structure of a C++ program – defining complex types – strings, vectors, iterators – quick intro: arrays and pointers Bookstore Example • Bookstore keeps a file of transactions • Each transaction records the sale of a particular book – ISBN (International Standard Book Number) – number of copies sold – price at which each copy was sold ex: 0-201-70353-X 4 24.9 Bookstore: Problem Definition • Bookstore owner wants to know: – number of copies of each title sold – total revenue from each book – average sales price of a book Bookstore: Designing the Solution • We need to get input, and produce output • We want to define a data structure to hold this data • We want to be able to test if two records are the same (ISBN) • We want to look at every transaction in the input Bookstore: Designing the Solution • How do we get the average sales price? Done manually… – look at all transactions with the same ISBN • but how will we know when we can stop reading in transaction information? – do a weighted average: • for each ISBN: – sum of copies sold * price / total number of copies sold • How can we do it in C++? – Need: new data types, if statements, loops Control Structures • if statements • loops – for – while – do-while if statements if (condition) if_body; Performs if_body only in the case when condition is true // sum from 0-10, even numbers only int sum=0; for(int ctr=0;ctr<=10;ctr++) { if(ctr % 2 == 0) { sum+=ctr; } } Loops • for • while • do-while for loop for(init-statement; condition; expression) for_body; Repeats for_body until condition is false, performing expression after each iteration int sum = 0; for(int ctr=0; ctr <= 10; ctr++) { sum += ctr; } while loop while (condition) while_body_statement ; Repeatedly tests condition, and then executes the while_body_statement until condition is false int ctr = 0, sum_to_ten = 0; while(ctr <= 10) { sum_to_ten += ctr; ++ctr; // ++ increments ctr } also: do { sum_to_ten += ctr; ++ctr; } while(ctr <= 10); I/O: A Closer Look • I/O is shorthand for input/output • You’ve seen this already: – std::cin, std::cout What’s going on here? I/O happens in C++ as part of the standard library (std), specifically the iostream library Standard library must be implemented by every C++ compiler The preprocessor directive #include <iostream> or #include <iostream.h> …tells the C++ preprocessor to use the iostream library I/O: A Closer Look • iostream defines four IO objects – “standard input” • istream std::cin – “standard output” • ostream std::cout – “standard error” • ostream std::cerr – “see-log” • ostream std::clog • Why streams? – istream and ostream objects can also be created for getting input and output out of files I/O: A Closer Look UNIX interlude: “standard input”, “standard output” and “standard error” are UNIX concepts You can redirect output of a program into a file depending on which stream it’s in: stdout: ./a.out 1> out_file stderr: ./a.out 2> err_file stdout and stderr: ./a.out > outerr_file You can also use a file as user input similarly: stdin: ./a.out < in_file I/O: A Closer Look When you see the line: std::cout << “Enter two numbers:” << std::endl; …the << is actually the output operator, which is a binary operator producing an ostream object (std::cout) std::endl is a manipulator – in this case flushes the buffer to the standard output Creating Classes • Moving beyond primitive types: – class types are complex types • Need to know: – what is the name of a class? – where is it defined? – what operations can it do? Bookstore redux: Classes We have a Sales_item • stores ISBN • keeps track of: – number of copies sold – revenue – average sales price • Lives in Sales_item.h – header file storing the class definition Sales_item class • Operations: – Use addition operator + to add two Sales_items – Use input operator << to read a Sales_item – Use output operator >> to write a Sales_item – Use assignment operator = to assign one Sales_item to another – Call same_isbn function to see if two Sales_items are the same book Sales_item class #include <iostream> #include “Sales_item.h” int main() { Sales_item book; // read ISBN, number of copies sold, and sales price std::cin >> book; // write ISBN, number of copies sold, total revenue, and average price std::cout << book << std::endl; return 0; } Sales_item class Input: 0-201-70353-X 4 24.99 Output: 0-201-70353-X 4 99.96 24.99 Sales_item class #include <iostream> #include “Sales_item.h” int main() { Sales_item item1, item2; // read two transactions std::cin >> item1 >> item2; // print their sum std::cout << item1 + item2 << std::endl; return 0; } Sales_item class Input: 0-201-78345-X 3 20.00 0-201-78345-X 2 25.00 Output: 0-201-78345-X 5 110 22 Sales_item class #include <iostream> #include “Sales_item.h” int main() { Sales_item item1, item2; // read two transactions std::cin >> item1 >> item2; // print their sum, if the same isbn: if(item1.same_isbn(item2)) { std::cout << item1 + item2 << std::endl; return 0; // success! } else { std::cerr << “Data must refer to same ISBN” << std::endl; return -1; // failure } } Bookstore: Putting it together • Now we have all of the components to write our bookstore program! Class Types • We can define an empty class for Sales_item: class Sales_item { public: // operations on Sales_item objects will go here private: std::string isbn; unsigned units_sold; double revenue; }; Don’t forget the semicolon! Class Types • We could also have defined Sales_item as a struct: struct Sales_item { // struct members are by default public // operations on Sales_item objects private: std::string isbn; unsigned units_sold; double revenue; }; Only difference from class: struct members are by default public; class members are by default private Writing Header Files • Class definitions go into a header file (extension .h) • Implementation for the definitions goes elsewhere Sales_item.h: definition for Sales_item Implementation goes in a separate source file Every file that uses Sales_item must #include “Sales_item.h” Writing Header Files • Headers contain: – class definitions – extern variable declarations – function declarations • Headers should NOT define variables and objects, only declare them (extern keyword) • Headers sometimes must #include other header files – Sales_item.h needs string.h, since it uses std::string – This means you need to be careful not to #include a header more than once! Writing Header Files • To keep this from happening: – more preprocessor directives #ifndef SALESITEM_H #define SALESITEM_H // definition of Sales_item and related goes here #endif Setting aside Bookstore • Enough about bookstore for now; let’s talk about library types • We’ll get back to the detailed implementation of how to make Sales_item a reality Library Types • We talked briefly about the standard library std::cout meaning: std is the namespace, :: is the scope operator, cout is an object in the namespace • You’ve seen some code that just uses cout by itself • Need to declare the namespace first: using namespace std; Library Types • We can accomplish the same thing to bring specific objects into the namespace like so: using std::cin; Strings • Strings! Memory interlude: the term “string” comes from shorthand for character string, which is what strings are in just about any language (we’ll see what this means when we talk about arrays and pointers) In C++: std::string, like many string implementations, has more functionality than a plain character string • To make a string, we need to: #include <string> using std::string; Strings • Initializing a string: – string s1; // s1 is the empty string • (why is this initialized? it uses the default constructor – we’ll talk more about this later) – string s2(s1); // copies s1 into s2 – string s3(“value”); // initializes s3 as a copy of the // string literal – string s4(n, ‘c’); // initializes s4 with n copies of // ‘c’ Strings • Initializing a string: – string s1; // s1 is the empty string • (why is this initialized? it uses the default constructor – we’ll talk more about this later) – string s2(s1); // copies s1 into s2 – string s3(“value”); // initializes s3 as a copy of the // string literal – string s4(n, ‘c’); // initializes s4 with n copies of // ‘c’ Why are we doing it this way? copy-initialization vs. direct-initialization; related to memory Strings • Like Sales_item objects, we can read these off of istream objects, and print them to ostream objects string s; // note: this is initialized! cin >> s; cout << s << endl; • Or we can use getline: string line; while (getline(cin, line)) cout << line << endl; • Ordinarily the input operator (>>) only reads a word at a time (space-delimited) Strings Operation s.empty() Returns true if s is empty; otherwise false s.size() Number of characters in s (Not an int! Instead, it’s string::size_type) s[n] Returns nth character of s (0-indexed) s1 + s2 Returns a string that concatenates s1 and s2 s1 = s2 Replaces all of the characters in s1 with a copy of s2 v1 == v2 Returns true if equal, otherwise false !=, <, <=, >, and >= Usual meanings Strings • String size: – string::size_type is either an unsigned int or unsigned long – companion type for the string type – If we used an int, this limits the length of strings to twice the size of an int – many files would easily exceed that and need to be held in a single variable • String ordering: – Think alphabetical, where the alphabet is ASCII • Subscripting: – Subscripting results in an lvalue, so we can change the middle of a string – Any integral type (char, bool, int) can be used for subscripting; we use string::size_type typically Vectors • A vector is a collection of objects of one type • Indexed by integers • Need to include and declare it: #include <vector> using std::vector; • Class template: – Allow us to write a single class or function to hold a variety of types vector<int> ivec; vector<Sales_item> Sales_vec; Vectors • Initialization: – vector<T> v1; // vector that holds objects // of type T – vector<T> v2(v1); // v2 is a copy of v1 – vector<T> v3(n, i); // v3 has n elements with // value i – vector<T> v4(n); // v4 has n copies of a // value-initialized object Vectors • Vector initialization – vector<int> ivec1; // ivec1 is an int vector – vector<int> ivec2(ivec1); // OK – vector<string> svec(ivec1); // BAD – vector<string> svec(10, “hi!”); // 10 strings of “hi!” Vectors • Vectors grow dynamically; you can add elements at run-time • Unlike arrays (from C or Java, and many other languages), you don’t need to know how big they’re going to be ahead of time • Vectors will populate themselves by default at initialization with either the default constructor of the type, or an element initializer (0 in the case of int) for basic types Vectors • Which of these vector definitions are wrong? vector< vector<int> > ivec; vector<string> svec = ivec; vector<string> svec(10, “null”); Vectors • How many elements are there in each of these vectors? – – – – – – vector<int> ivec1; vector<int> ivec2(10); vector<int> ivec3(10, 42); vector<string> svec1; vector<string> svec2(10); vector<string> svec3(10, “hello”); • What are the values of the elements for each? Vectors Operations v.empty() Returns true if the vector is size 0 v.size() Returns the number of elements in v v.push_back(t) Increases size of v; adds value t to the end v[n] Returns element at position n in v v1 = v2 Replaces elements in v1 with a copy of elements in v2 v1 == v2 Tests if v1 and v2 are equal !=, <, <=, >, >= comparison is “alphabetical” You MUST use v.push_back(t) to put a new element in! Unlike in other languages, v[n] = t; is NOT valid unless n < v.size() Iterating through Vectors • We learned about for loops, let’s use them on vectors! vector<int> ivec; for (vector<int>::size_type ix = 0; ix != 10; ++ix) ivec.push_back(ix); Iterating through Vectors • We can actually do this with another syntax • Vector has a companion type, vector<T>::iterator • Designed to move through every element in a vector vector<int> ivec; vector<int>::iterator iter = ivec.begin(); iter now refers to ivec[0] (unless ivec was empty) Iterating through Vectors • There’s also an ivec.end(), but it doesn’t refer to an element in the vector – it tells us when we’re done (sentinel) • In order to access elements through an iterator, we must dereference it *iter = 0; • So our loop can now be written as: for (vector<int>::iterator iter=ivec.begin(); iter != ivec.end(); ++iter) *iter = 0; How would we use iterators to write this as a while loop? Iterating through Vectors • There’s also a const_iterator • Used when we will only be reading from the vector, and not changing the elements • A const_iterator is not a const iterator • You can move iterators forward n elements as follows: iter = iter + n; iter = iter - n; • You can also track two points in the vector with two iterators, and find out how far apart they are: iter1 – iter2; • Mostly won’t need this, but it’s good to know =) Arrays • If you’ve programmed before, you’ve heard of these – (lists in Python) • Like vectors, but must be a fixed size ahead of time • Why? – Must allocate space in memory Pointers: A quick introduction • If you’ve done coding or been around computer science, you’ve probably heard about pointers • Arrays in C++ (as well as C) are built on pointers • A pointer is a variable that holds a memory location, rather than data Pointers: A quick introduction • We can create variables, then store their locations in pointer variables int var = 0; int *var_ptr = &var; • * is the dereference operator from before • Arrays are a series of memory locations • Iterating through them involves moving the pointer forward Tomorrow • more on classes: how is Sales_item getting defined? • arrays, pointers, and more, oh my!