std Library of C Part 2 vector n
std Library of C++ Part 2
vector n n n vector is a collection of objects of a single type 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.
Class template n n n vector is a class template Templates allow single class (or function) definition to be used on a variety of types So one vector variable/object can hold ints Another vector object can hold strings A third vector object can hold objects of user defined classes like Sales_item
vector example n n n #include <vector> using std: : vector; vector<int> ivec; // ivec holds objects of type int vector<Sales_item> Sales_vec; // holds Sales_items The type of object to be held in a vector is passed within angle brackets
Types n n Vector is not a type; it is a class template The type is known only after the arguments of the class template are specified So vector<int> is a type And vector <string> is another type.
vector initialization n vector<T> v 1; n n vector<T> v 2(v 1); n n vector that holds objects of type T; Default constructor v 1 is empty v 2 is a copy of v 1 vector<T> v 3(n, i); n v 3 has n elements with value i
vector initialization contd. n vector<int> ivec 4(10, -1); n n // 10 elements, each initialized to -1 vector<string> svec(10, "hi!"); n // 10 strings, each initialized to "hi!"
vector. push_back() n n n 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. This involves creating space for a new element at the end of the vector.
Adding elements to a vector n n n n // read words from the standard input and // store them as elements in a vector string word; vector<string> text; // empty vector while (cin >> word) { text. push_back(word); // append word to text }
Accessing elements of a vector n n // reset the elements in the vector to zero for (vector<int>: : size_type ix = 0; ix != ivec. size(); ++ix) ivec[ix] = 0;
Subscripting does not add!! n n n n vector<int> ivec; // empty vector for (vector<int>: : size_type ix = 0; ix != 10; ++ix) ivec[ix] = ix; // disaster: ivec has no elements An element must exist in order to subscript it; Elements are not added when we assign through a subscript.
Correct way to add n n for (vector<int>: : size_type ix = 0; ix != 10; ++ix) ivec. push_back(ix); // ok: adds new element with value ix
Assignment 3 C n n n 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. Test your program with small, medium and very large text input files. Notice how fast the program runs.
Assignment 3 C contd. n Optional: For the ambitious, time stamp and print out the time taken by the read part of the program.
IO Library Streams n n 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.
IOStream n The iostream header has: n n istream (input stream) type, which supports input operations cin (pronounced see-in) an istream object that reads the standard input ostream (output stream) type, which provides output operations cout (pronounced see-out) an ostream object that writes to the standard output
Facilities Used So Far n Some facilities that we used were: n n n operator >>, which is used to read input from an istream 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
Reading and Writing Files n n n 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) Ideally we should be able to use >> and << to operate on a named file too.
File Stream n fstream header defines the types used to read and write named files: n n n ifstream type reads from a file ofstream type writes to a file >>, << operators can be used to i/o on file streams
… File Stream n n ifstream infile; // unbound input file stream ofstream outfile; // unbound output file stream infile and outfile need to be bound to a named file. infile. open("in"); // open file named "in" in the current directory outfile. open("out"); // open file named "out" in the current directory
Testing open success n n n n Did open succeed? ? // check that the open succeeded if (!infile) { cerr << "error: unable to open input file: " << ifile << endl; return -1; }
Defining ifstream object and opening file in one stmt. n n n ifstream infile("in"); Defines/declares infile object and also opens file “in” and binds it to infile and opens the file. Success/failure check: if (infile) …
Reading/Writing n n n n Reading a string from an ifstream object string word; infile >> word; //Reads next string from infile // into word Writing a string into an ofstream object ofstream outfile(“out”); outfile << “Hello World”;
Example Programs n n See filecin. cpp See fileio. cpp
String Streams n n n In-Memory input/output where a stream is attached to a string (in program memory) istringstream type reads from a string istringsteam strm(line); n n n Given that line is a string strm is an istringstream bound to the string line strm >> strword; n Reads next word from line into strword
Counting words & lines n See count. Word. NLine. cpp (Not from book code)
Assignment 3 d n Write a Line. Size. Search 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. ]
Assignment 3 d n n 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.
Assignment 3 d n 3) Now allow user to search for any line of a specified line size. n n Show all the matching lines, preceded by the line number, line size OR, if no matching lines are found, a message to that effect. Allow user to keep searching for as many times as he wants. On user keying in End-Of-Data (Ctrl-D), Quit program
More Details n For more details on IO Library and streams, interested students can read Chapter 8: IO Library from course book.
Book Source Code Copyright Note n The course book is C++ Primer, 4 th 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.
- Slides: 31