Presentation is loading. Please wait.

Presentation is loading. Please wait.

Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.

Similar presentations


Presentation on theme: "Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in."— Presentation transcript:

1 std Library of C++ Part 2

2 vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in a vector has an associated integer index (like an array element) Each object in a vector has an associated integer index (like an array element) As with string, vector class itself manages memory associated with the collection. As with string, vector class itself manages memory associated with the collection.

3 Class template vector is a class template vector is a class template Templates allow single class (or function) definition to be used on a variety of types Templates allow single class (or function) definition to be used on a variety of types So one vector variable/object can hold ints So one vector variable/object can hold ints Another vector object can hold strings Another vector object can hold strings A third vector object can hold objects of user defined classes like Sales_item A third vector object can hold objects of user defined classes like Sales_item

4 vector example #include #include using std::vector; using std::vector; vector ivec; // ivec holds objects of type int vector ivec; // ivec holds objects of type int vector Sales_vec; // holds Sales_items vector Sales_vec; // holds Sales_items The type of object to be held in a vector is passed within angle brackets The type of object to be held in a vector is passed within angle brackets

5 Types Vector is not a type; it is a class template Vector is not a type; it is a class template The type is known only after the arguments of the class template are specified The type is known only after the arguments of the class template are specified So vector is a type So vector is a type And vector is another type. And vector is another type.

6 vector initialization vector v1; vector v1; vector that holds objects of type T; vector that holds objects of type T; Default constructor Default constructor v1 is empty v1 is empty vector v2(v1); vector v2(v1); v2 is a copy of v1 v2 is a copy of v1 vector v3(n, i); vector v3(n, i); v3 has n elements with value i v3 has n elements with value i

7 vector initialization contd. vector ivec4(10, -1); vector ivec4(10, -1); // 10 elements, each initialized to -1 // 10 elements, each initialized to -1 vector svec(10, "hi!"); vector svec(10, "hi!"); // 10 strings, each initialized to "hi!" // 10 strings, each initialized to "hi!"

8 vector.push_back() push_back() method takes an element value and puts that at the back of a vector push_back() method takes an element value and puts that at the back of a vector We can say that is pushes the element onto the back or end of the vector. We can say that is pushes the element onto the back or end of the vector. This involves creating space for a new element at the end of the vector. This involves creating space for a new element at the end of the vector.

9 Adding elements to a vector // read words from the standard input and // read words from the standard input and // store them as elements in a vector // store them as elements in a vector string word; string word; vector text; // empty vector vector text; // empty vector while (cin >> word) { while (cin >> word) { text.push_back(word); text.push_back(word); // append word to text // append word to text }

10 Accessing elements of a vector // reset the elements in the vector to zero // reset the elements in the vector to zero for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != ivec.size(); ++ix) ix != ivec.size(); ++ix) ivec[ix] = 0; ivec[ix] = 0;

11 Subscripting does not add!! vector ivec; // empty vector vector ivec; // empty vector for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != 10; ++ix) ix != 10; ++ix) ivec[ix] = ix; ivec[ix] = ix; // disaster: ivec has no elements // disaster: ivec has no elements An element must exist in order to subscript it; An element must exist in order to subscript it; Elements are not added when we assign through a subscript. Elements are not added when we assign through a subscript.

12 Correct way to add for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != 10; ++ix) ix != 10; ++ix) ivec.push_back(ix); ivec.push_back(ix); // ok: adds new element with value ix // ok: adds new element with value ix

13 Assignment 3C Read words from standard input till end of input, into a vector. Read words from standard input till end of input, into a vector. Write out all words (by retrieving them from the vector) to standard output separating each word by a newline. Write out all words (by retrieving them from the vector) to standard output separating each word by a newline. Test your program with small, medium and very large text input files. Notice how fast the program runs. Test your program with small, medium and very large text input files. Notice how fast the program runs.

14 Assignment 3C contd. Optional: For the ambitious, time stamp and print out the time taken by the read part of the program. Optional: For the ambitious, time stamp and print out the time taken by the read part of the program.

15 IO Library Streams We will have a very quick look at IO Library streams. We will have a very quick look at IO Library streams. C++ std library provides a family of types and objects that support I/O. C++ std library provides a family of types and objects that support I/O.

16 IOStream The iostream header has: The iostream header has: istream (input stream) type, which supports input operations istream (input stream) type, which supports input operations cin (pronounced see-in) an istream object that reads the standard input cin (pronounced see-in) an istream object that reads the standard input ostream (output stream) type, which provides output operations ostream (output stream) type, which provides output operations cout (pronounced see-out) an ostream object that writes to the standard output cout (pronounced see-out) an ostream object that writes to the standard output

17 Facilities Used So Far Some facilities that we used were: Some facilities that we used were: operator >>, which is used to read input from an istream object operator >>, which is used to read input from an istream object operator <<, which is used to write output to an ostream object operator <<, which is used to write output to an ostream object getline function, which takes a reference to an istream and a reference to a string and reads a word from the istream into the string getline function, which takes a reference to an istream and a reference to a string and reads a word from the istream into the string

18 Reading and Writing Files So far we have used the IO types and objects to read and write from stdin and stdout So far we have used the IO types and objects to read and write from stdin and stdout But programs often need to read and write named files (and not use redirection) But programs often need to read and write named files (and not use redirection) Ideally we should be able to use >> and > and << to operate on a named file too.

19 File Stream fstream header defines the types used to read and write named files: fstream header defines the types used to read and write named files: ifstream type reads from a file ifstream type reads from a file ofstream type writes to a file ofstream type writes to a file >>, >, << operators can be used to i/o on file streams

20 … File Stream ifstream infile; // unbound input file stream ofstream outfile; // unbound output file stream ifstream infile; // unbound input file stream ofstream outfile; // unbound output file stream infile and outfile need to be bound to a named file. infile and outfile need to be bound to a named file. infile.open("in"); // open file named "in" in the current directory infile.open("in"); // open file named "in" in the current directory outfile.open("out"); // open file named "out" in the current directory outfile.open("out"); // open file named "out" in the current directory

21 Testing open success Did open succeed?? Did open succeed?? // check that the open succeeded // check that the open succeeded if (!infile) { if (!infile) { cerr << "error: unable to open input file: " cerr << "error: unable to open input file: " << ifile << endl; << ifile << endl; return -1; return -1; } }

22 Defining ifstream object and opening file in one stmt. ifstream infile("in"); ifstream infile("in"); Defines/declares infile object and also opens file “in” and binds it to infile and opens the file. Defines/declares infile object and also opens file “in” and binds it to infile and opens the file. Success/failure check: if (infile) … Success/failure check: if (infile) …

23 Reading/Writing Reading a string from an ifstream object Reading a string from an ifstream object string word; string word; infile >> word; //Reads next string from infile infile >> word; //Reads next string from infile // into word // into word Writing a string into an ofstream object Writing a string into an ofstream object ofstream outfile(“out”); ofstream outfile(“out”); outfile << “Hello World”; outfile << “Hello World”;

24 Example Programs See filecin.cpp See filecin.cpp See fileio.cpp See fileio.cpp

25 String Streams In-Memory input/output where a stream is attached to a string (in program memory) In-Memory input/output where a stream is attached to a string (in program memory) istringstream type reads from a string istringstream type reads from a string istringsteam strm(line); istringsteam strm(line); Given that line is a string Given that line is a string strm is an istringstream bound to the string line strm is an istringstream bound to the string line strm >> strword; strm >> strword; Reads next word from line into strword Reads next word from line into strword

26 Counting words & lines See countWordNLine.cpp (Not from book code) See countWordNLine.cpp (Not from book code)

27 Assignment 3d Write a LineSizeSearch program that accepts one (and only one) agrument which is the input text filename. [Don't forget to check number of arguments passed to main. If it is not the expected number then immediately print an error message, followed by "Usage: 'argv[0]' file-name” and then exit.] Write a LineSizeSearch program that accepts one (and only one) agrument which is the input text filename. [Don't forget to check number of arguments passed to main. If it is not the expected number then immediately print an error message, followed by "Usage: 'argv[0]' file-name” and then exit.]

28 Assignment 3d 1) Read all lines from an input text file into memory (Till EOF). 1) Read all lines from an input text file into memory (Till EOF). 2) Then print stats about file (no. of lines), and print entire file with line number, line size: before each line. 2) Then print stats about file (no. of lines), and print entire file with line number, line size: before each line.

29 Assignment 3d 3) Now allow user to search for any line of a specified line size. 3) Now allow user to search for any line of a specified line size. Show all the matching lines, preceded by the line number, line size Show all the matching lines, preceded by the line number, line size OR, if no matching lines are found, a message to that effect. OR, if no matching lines are found, a message to that effect. Allow user to keep searching for as many times as he wants. Allow user to keep searching for as many times as he wants. On user keying in End-Of-Data (Ctrl-D), Quit program On user keying in End-Of-Data (Ctrl-D), Quit program

30 More Details For more details on IO Library and streams, interested students can read Chapter 8: IO Library from course book. For more details on IO Library and streams, interested students can read Chapter 8: IO Library from course book.

31 Book Source Code Copyright Note The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides. The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides.


Download ppt "Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in."

Similar presentations


Ads by Google