Docsity

Strings and Vectors - Data Structures - Lecture Notes | CSCI 1200, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
Data Structures — Lecture 2
Strings and Vectors
1 Overview of Lecture 2
The following topics will be covered
•Complete discussion of scope from Monday lecture.
•Strings
•Vectors as “smart arrays”
2 Background Reading
All reading references are to Ford&Topp,
•Strings: pp. 28-35
•Vectors: Chapter 4
Much of what is covered here is basic background for C++ programming and is covered in
virtually any introductory text.
3 C++ Strings
3.1 Example 1
Here is example output of a program that reads in a string and outputs a framed greeting.
Please enter your first name: Chuck
*****************
* *
* Hello, Chuck! *
* *
*****************
The program is on the next page.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Strings and Vectors - Data Structures - Lecture Notes | CSCI 1200 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures — Lecture 2

Strings and Vectors

1 Overview of Lecture 2

The following topics will be covered

  • Complete discussion of scope from Monday lecture.
  • Strings
  • Vectors as “smart arrays”

2 Background Reading

All reading references are to Ford&Topp,

  • Strings: pp. 28-
  • Vectors: Chapter 4

Much of what is covered here is basic background for C++ programming and is covered in virtually any introductory text.

3 C++ Strings

3.1 Example 1

Here is example output of a program that reads in a string and outputs a framed greeting.

Please enter your first name: Chuck


  • Hello, Chuck! *

The program is on the next page.

// ask for a person’s name, and generate a framed greeting #include #include

int main() { std::cout << "Please enter your first name: "; std::string name; std::cin >> name;

// build the message that we intend to write const std::string greeting = "Hello, " + name + "!";

// build the second and fourth lines of the output const std::string spaces( greeting.size(), ’ ’ ); const std::string second = "* " + spaces + " *";

// build the first and fifth lines of the output const std::string first(second.size(), ’*’);

// write it all std::cout << std::endl; std::cout << first << std::endl; std::cout << second << std::endl; std::cout << "* " << greeting << " *" << std::endl; std::cout << second << std::endl; std::cout << first << std::endl;

return 0; }


3.2 string objects

  • A string is an object type defined in the standard library to contain a sequence of characters.
  • The string type, like all types (including int, double, char, float), defines an in- terface, which includes construction (initialization), operations, functions (methods), and even other types(!).
  • When an object is created, a special function is run called a “constructor”, whose job it is to initialize the object. The greeting example code exhibits three ways of constructing string objects: - By default to create an empty string
  • Java objects must be created using new, as in

String name = new String("Chris");

This is not necessary in C++. The C++ (approximate) equivalent to this example is

std::string name("Chris");

On the other hand, there is a new operator in C++ and its behavior is somewhat similar to the new operation in Java. We will study it later in the semester.

3.5 More on strings

  • Strings behave like arrays when using the subscript operator [].
    • This gives access to the individual characters in the string.
    • Subscript 0 corresponds to the first character.
    • For example, given std::string a = "Susan"; Then a[0] == ’S’ and a[1] == ’u’ and a[4] == ’n’.
  • Strings define a special type, which is the type returned by the string functions size() and length():

string::size_type

  • The :: notation means that size type is defined within the scope of the string type.
  • string::size_type is generally equivalent to unsigned int.
  • You may have compiler warnings and potential compatibility problems if you compare an int variable to a.size().

3.6 Example Problem: Writing a name along a diagonal

Here is a more interesting problem:

What is your first name? Peter


  • P *
  • e *
  • t *
  • e *
  • r *

3.7 Solution Approach

  • Initial stuff: read the name, and output a blank line, as in an earlier example.
  • Let’s think about the main output: think of the output region as a grid of rows and columns: - How big is this region? - What gets output where?
  • This leads to an implementation with two nested loops, and conditionals used to guide where characters should be printed.

std::cout << ’\n’;

and

std::cout << std::endl;

What is the difference?

  • C++ streams store their output in an output buffer. This buffer is not immediately written to a file or displayed on your screen. The reason is that the writing process is much slower than the other computations. It is much faster overall when output is buffered and then done “all at once” — in large chunks — when the buffer is full.
  • Thus, just outputting the ’\n’ — the end-of-line character — just adds one more character to the buffer.
  • Outputting std::endl has two effects:
    • Outputting the ’\n’ character, and
    • Causing the buffer to be “flushed” — actually output to the file or screen.
  • Why should you care?
    • When your program crashes, the contents of the output buffer are lost and not actually output. As a result, when looking at your output it often appears that your program crashed much earlier than it actually did. Therefore, using std::endl helps greatly with debugging.
    • But, using std::endl can substantially slow down a program that has a lot of output. Therefore, when a program is fully debugged (and needs to run at a reasonable speed), std::endl should be replaced by ’\n’.

3.10 Loop Invariants

  • Definition: a loop invariant is a logical assertion that is true at the start of each iteration of a loop. - In for loops, the “start” is defined as coming after the initialization/increment and termination test, but before execution of the next loop iteration.
  • An invariant is stated in a comment; it is not part of the actual code.
  • It helps determine:
    • The conditions that may be assumed to be true at the start of each iteration.
    • What must be done in each iteration.
    • What must be done at the end of each iteration to restore the invariant.
  • Analyzing the code relative to the stated invariant also helps explain the code and think about its correctness.

3.11 L-Values and R-Values

  • Consider the simple code

string a = "Kim"; string b = "Tom"; a[0] = b[0];

String a is now "Tim".

  • No big deal, right? Wrong!
  • Let’s look closely at the line:

a[0] = b[0];

and think about what happens.

  • In particular, what is the difference between the use of a[0] on the left hand side of the assignment statement and b[0] on the right hand side?
  • Syntactically, they look the same. But,
    • The expression b[0] gets the char value, ’T’, from string location 0 in b. This is an r-value
    • The expression a[0] gets a reference to the memory location associated with string location 0 in a. This is an l-value.
    • The assignment operator stores the value in the referenced memory location.

The difference between an r-value and an l-value will be especially significant when we get to writing our own operators.

3.12 A Second Solution To Our Diagonal Name Problem

Here are ideas for a second solution:

  • Think about what changes from one line to the next.
  • Suppose we had a “blank line” string, containing only the beginning and ending asterisks and the intervening blanks.
  • We could overwrite the appropriate blank character, output the string, and then restore the blank character.

The second solution will be posted on line.

4 Standard Library (STL) Vectors

4.1 Problem: Grade Statistics

  • Read an unknown number of grades.
  • Compute:
    • Mean (average)
    • Standard deviation
    • Median (middle value)
  • Accomplishing this requires the use of vectors.

4.2 Standard Deviation

  • Definition: if a 0 , a 1 , a 2 ,... , an− 1 is a sequence of n values, and μ is the average of these values, then the standard deviation is [ ∑n− 1 i=0 (ai^ −^ μ) 2 n − 1

] 12

  • Computing this equation requires two passes through the values:
    • Once to compute the average
    • A second time to compute the standard deviation
  • Thus, we need a way to store the values.
  • The only tool we have so far is arrays. But arrays are fixed in size and we don’t know in advance how many values there will be.
  • This illustrates one reason why we generally will use standard library vectors instead of arrays.

4.3 Vectors

  • Standard library “container class” to hold sequences.
  • A vector acts like a dynamically-sized, one-dimensional array.
  • Capabilities:
    • Holds objects of any type
    • Starts empty unless otherwise specified
    • Any number of objects may be added to the end — there is no limit on size.
    • It can be treated like an ordinary array using the subscripting operator.
    • There is NO automatic checking of subscript bounds.

4.4 Computing the Standard Deviation

A program to compute the standard deviation is provided with these notes (average and deviation.cpp). We will use this to discuss the use of vectors.

  • Header files:

#include

defines the vector class

#include

includes the C standard math library prototypes and declarations so that we can use the sqrt function.

  • The following creates an empty vector of integers:

vector scores;

Vectors are an example of a templated container class.

  • The angle brackets < > are used to specify the type of object (the “template type”) that will be stored in the vector.
  • push back is a vector function to append a value to the end of the vector, increasing its size by one. This is an O(1) operation (on average).
  • There is NO corresponding push front operation for vectors.
  • size is a function defined by the vector type (the vector class) that returns the number of items stored in the vector.
  • After vectors are initialized and filled in, they may be treated just like arrays.
  • In the line sum += scores[i]; scores[i] is an “r-value”, accessing the value stored at location i of the vector.
  • We could also write statements like scores[4] = 100; to change a score. Here scores[4] is an “l-value”, providing the means of storing 100 at location 4 of the vector.
  • It is the job of the programmer to ensure that any subscript value i that is used is legal —- at least 0 and strictly less than scores.size().

4.8 Passing Vectors (and Strings) As Parameters

The following outlines rules for passing vectors as parameters. The same rules apply to passing strings.

  • If you are passing a vector as a parameter to a function and you want to make a (permanent) change to the vector, then you should pass it by reference. - This is illustrated by the function read scores in the program median grade. - This is very different from the behavior of arrays as parameters.
  • What if you don’t want to make changes to the vector or don’t want these changes to be permanent? - The answer we’ve learned so far is to pass by value. - The problem is that the entire vector is copied when this happens!
  • The solution is to pass by constant reference: pass it by reference, but make it a constant so that it can not be changed. - This is illustrated by the functions compute avg and std dev and compute median in the program median grade.
  • As a general rule, you should not pass a container object such as a vector or a string by value because of the cost of copying. There are rare circumstances in which this rule may be violated, but not in Data Structures.

4.9 Initializing a Vector — The Use of Constructors

  • Here is an example of several different ways to initialize a vector:

vector a; // # int n = 100; vector b( 100, 3.14 ); // # vector c( n*n ); // # vector d( b ); // # vector e( b ); // #

  • Version #1 “constructs” an empty vector of integers. Values must be placed in the vector using push_back.
  • Version #2 constructs a vector of 100 doubles, each entry storing the value 3.14. New entries can be created using push_back, but these will create entries 100, 101, 102, etc.
  • Version #3 constructs a vector of 10,000 ints, but provides no initial values for these integers. Again, new entries can be created for the vector using push_back. These will create entries 10000, 10001, etc.
  • Version #4 constructs a vector that is an exact copy of vector b.
  • Version #5 is a compiler error because no constructor exists to create an int vector from a double vector. These are different types.

4.10 Exercises

  1. After the above code constructing the three vectors, what will be output by the following statement?

cout << a.size() << endl << b.size() << endl << c.size() << endl;

  1. Write code to construct a vector containing 100 doubles, each having the value 55.5.
  2. Write code to construct a vector containing 1000 doubles, containing the values 0, 1,√ 2,

5, etc. Write it two ways, one that uses push_back and one that does not use push_back.

4.11 Additional Example — Alphabetize Strings

Posted on-line, as part of the zip file containing code from this lecture, is an additional example of using vectors, strings and the sort function to alphabetize last names. The source code will also be posted on the web. This is an important example for future homeworks.

5 Summary

  • C++ strings from the standard library hold sequences of characters and have a so- phisticated set of operations defined on them.
  • Vectors, also from the standard library, can be thought of as smart, dynamically-sized arrays. Vectors should almost always be used instead of arrays, but as we will see vectors are defined internally in terms of arrays.