Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ crash course Class 3 designing C++ programs, classes, control structures.

Similar presentations


Presentation on theme: "C++ crash course Class 3 designing C++ programs, classes, control structures."— Presentation transcript:

1 C++ crash course Class 3 designing C++ programs, classes, control structures

2 Types Last time: basic types and variables Today: – structure of a C++ program – defining complex types – strings, vectors, iterators – quick intro: arrays and pointers

3 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

4 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

5 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

6 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

7 Control Structures if statements loops – for – while – do-while

8 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; }

9 Loops for while do-while

10 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; }

11 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);

12 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 or #include …tells the C++ preprocessor to use the iostream library

13 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

14 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

15 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

16 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?

17 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

18 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

19 Sales_item class #include #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; }

20 Sales_item class Input: 0-201-70353-X 4 24.99 Output: 0-201-70353-X 4 99.96 24.99

21 Sales_item class #include #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; }

22 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

23 Sales_item class #include #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 }

24 Bookstore: Putting it together Now we have all of the components to write our bookstore program!

25 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!

26 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

27 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”

28 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!

29 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

30 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

31 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;

32 Library Types We can accomplish the same thing to bring specific objects into the namespace like so: using std::cin;

33 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 using std::string;

34 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’

35 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

36 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)

37 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

38 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

39 Vectors A vector is a collection of objects of one type Indexed by integers Need to include and declare it: #include using std::vector; Class template: – Allow us to write a single class or function to hold a variety of types vector ivec; vector Sales_vec;

40 Vectors Initialization: – vector v1; // vector that holds objects // of type T – vector v2(v1); // v2 is a copy of v1 – vector v3(n, i); // v3 has n elements with // value i – vector v4(n); // v4 has n copies of a // value-initialized object

41 Vectors Vector initialization – vector ivec1; // ivec1 is an int vector – vector ivec2(ivec1); // OK – vector svec(ivec1); // BAD – vector svec(10, “hi!”); // 10 strings of “hi!”

42 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

43 Vectors Which of these vector definitions are wrong? vector > ivec; vector svec = ivec; vector svec(10, “null”);

44 Vectors How many elements are there in each of these vectors? – vector ivec1; – vector ivec2(10); – vector ivec3(10, 42); – vector svec1; – vector svec2(10); – vector svec3(10, “hello”); What are the values of the elements for each?

45 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()

46 Iterating through Vectors We learned about for loops, let’s use them on vectors! vector ivec; for (vector ::size_type ix = 0; ix != 10; ++ix) ivec.push_back(ix);

47 Iterating through Vectors We can actually do this with another syntax Vector has a companion type, vector ::iterator Designed to move through every element in a vector vector ivec; vector ::iterator iter = ivec.begin(); iter now refers to ivec[0] (unless ivec was empty)

48 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 ::iterator iter=ivec.begin(); iter != ivec.end(); ++iter) *iter = 0; How would we use iterators to write this as a while loop?

49 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 =)

50 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

51 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

52 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

53 Tomorrow more on classes: how is Sales_item getting defined? arrays, pointers, and more, oh my!


Download ppt "C++ crash course Class 3 designing C++ programs, classes, control structures."

Similar presentations


Ads by Google