sábado, 30 de noviembre de 2013

String and Vectors Part 2

The Standard string Class

The string class allows the programmer to treat strings as a basic data type.  The string class is defined in the string library and the names are in the standard namespace.
To declare a string class we use: #include <string>

Variables of type string can be assigned with the = operator.  For example:

string s1, s2, s3;
...
s3 = s2;

Variable of type string can be concatenated with the + operator.  For example:

string s1, s2, s3;
...
s3 = s1 + s2;

If s3 is not large enough to contain s1 + s2, more space is allocated.

The default string constructor initializes the string to the empty string.  Another string constructor takes a C-string argument.  For example:

string phrase;               // empty string
string noun ("ants");     // a string version of "ants"


Mixing string and C-string

It is natural to work with strings in the following manner

string phrase = "I love" + adjective + " " + noun + "!";

It is not so easy for C++! It must either convert the null-terminated C-strings, such as "I love", to strings, or it must use an overloaded + operator that works with strings and C-strings.

I/O with Class string

  • The insertion operator << is used to output object of type string.
  • The extraction operator >> can be used to input data for objects of type string.
    • >> skips whitespace and stop on encountering more whitespace
    • >> cannot be used to read a blank character
getline and Type string


A getline function exists to read entire lines into a string variable.  This version of getline is not a member of the istream class, it is a non-member function.

Syntax for using getline with string objects:

getline(Istream_Object, String_Object);

Remember: To read one character at a time use cin.get (reads values of type char, not type string).

Another version of getline...
  • The versions of getline we have seen, stop reading at the end of line marker '\n'
  • getline can stop reading at a character specified in the argument list
    • This code stop reading when a '?' is read:
                                string line;
                                cout << "Enter some input:\n";
                                getline(cin, line, '?');

getline returns a reference to its first arguments.  For example, this code will read in a line of text into s1 and
a string of non-whitespace characters into s2:


These are the declarations of the versions of  getline for string objects we have seen:
  • istream& getline(istream& ins, string& str_var, char delimiter);
  • istream& getline(istream& ins, string& str_var);
Recall cin >> n skips whitespace to find what it is to read then stops reading when whitespace is found.  cin >> leaves the '\n' character in the input stream.  For example:

int n;
string line;
cin >> n;
getline(cin, line);

One member that we can used to read and discard all the characters, including '\n' that remain in a line is the ignore member function.  For example:

cin.ignore(1000, '\n');
reads up to 1000 characters or to '\n'

ignore takes two arguments:  First, the maximum number of characters to discard and second, the character that stops reading and discarding.  

The string class allows the same operations we used with C-string... and more.
Characters in a string object can be accessed as if they are in an array.

The string class member function length returns the number of characters in the string object.  For example:

int n = string_var.length( );

at is an alternative to using []'s to access characters in a string.  at checks for valid index value.  Fox example:

string str("Mary");
cout << str[6] << endl;
cout << str.at(6) << endl;
str[2] = 'X';
str.at(2) = 'X';

Other string class functions are found in...


Comparison of strings:

Comparison operators work with string objects.
  • Objects are compared using lexicographic order (Alphabetical ordering using the order of symbols in the ASCII character set.).
  • = = returns true if two string objects contain the same characters in the same order.
  • <, >, <=, >= can be used to compare string objects.

The substr member function is used to locate a substring within a string.

string Object to C-strings:
 

Recall the automatic conversion from C-string to string: 

char a_c_string[] = "C-string";
string_variable = a_c_string;
 
strings are not converted to C-strings.  Both of these statements are illegal:

a_c_string = string_variable;
strcpy(a_c_string, string_variable);

The string class member function c_str returns the C-string version of a string object. For Example:

strcpy(a_c_string, string_variable.c_str( ) );
 
This line is still illegal:

a_c_string = string_variable.c_str( ) ;

Recall that operator = does not work with C-strings

Vectors

Vectors are like arrays that can change size as your program runs.  They have a base type.
To declare an empty vector with base type int:

vector<int> v;

<int> identifies vector as a template class.
You can use any base type in a template class:

vector<string> v;

Vectors elements are indexed starting with 0.

  • [ ]'s are used to read or change the value of an item:

  •                     v[i] = 42;
                        cout << v[i];

    [ ]'s cannot be used to initialize a vector element.

    Elements are added to a vector using the member function push_back.  push_back adds an element in the next available position.  For example:

    vector<double> sample;
    sample.push_back(0.0);
    sample.push_back(1.1);
    sample.push_back(2.2);

    The member function size returns the number of elements in a vector.  For example, to print each element of a vector given the previous vector initialization:

    for (int i= 0; i < sample.size( ); i++)
    cout << sample[i] << endl;

    The vector class member function size returns an unsigned int (non-negative integers).

    A vector constructor exists that takes an integer argument and initializes that number of elements.  For example:

    vector<int> v(10);

    initializes the first 10 elements to 0
    v.size( ) would return 10
      • []'s can now be used to assign elements 0 through 9
      • push_back is used to assign elements greater than 9
    The vector constructor with an integer argument initializes elements of number types to zero and they initializes elements of class types using the default constructor for the class.

    To use the vector class, we include the vector library: #include<vector>

    More about vectors...
    • The assignment operator with vectors does an element by element copy of the right hand vector.
    • Attempting to use [ ] to set a value beyond the size of a vector may not generate an error.
    • A vector's capacity is the number of elements allocated in memory.
    • Size is the number of elements initialized.
    • When a vector runs out of space, the capacity is automatically increased.
    • When efficiency is an issue, the member function reserve can increase the capacity of a vector.  For example:
      • v.reserve(32); // at least 32 elements
      • v.reserve(v.size( ) + 10); // at least 10 more
    • resize can be used to shrink a vector.  For example:
      • v.resize(24); //elements beyond 24 are lost

    No hay comentarios.:

    Publicar un comentario