Arrays - PowerPoint PPT Presentation

1 / 32
About This Presentation
Title:

Arrays

Description:

C Style Strings use the STL (Standard Template Library) to store strings. ... style Strings?? I can think of at least 4 reasons: Why learn the old style ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 33
Provided by: chrisf2
Category:
Tags: arrays | style

less

Transcript and Presenter's Notes

Title: Arrays


1
Arrays
  • Class 8 Little more on Sorting, Structs, Multi
    Dimensional Arrays, C style strings, STL strings

2
Sorting
  • Bubble Sort Demonstration

3
Selection Sort
  • Selection Sort

4
Structures (Structs)
  • A structure, or struct, provides a means of
    grouping variables under a single name for easier
    handling and identification.
  • Structures may be copied to and assigned.
  • Structs are also useful in passing groups of
    logically related data into functions.

5
Structures
  • A structure is declared by using the keyword
    struct followed by a structure tag followed by
    the body of the structure.
  • The variables or members of the structure are
    declared within the body.
  • So, an example of a structure that would be
    useful in representing X,Y coordinates would be
  • struct point     int x     int y

6
Structures
  • You can then access and initialize variables in a
    struct with the dot ( . ) operator.
  • point starting_coord
  • starting_coord.x100
  • starting_coord.y200
  • cout ltltstarting_coord.x // prints 100

7
Structures
  • Structures can be defined with any mix or types
  • struct Person
  • char32 name
  • int ssn
  • int age
  • You can use these as any other variables You
    can create Arrays, etc.
  • Person classroster24

8
Multiple-Subscripted Arrays
  • So far, we have only examined single dimensional
    arrays.
  • It turns out you can also create 2,3, 4, 5
    dimensional arrays.
  • In fact, the ANSI C specification states that
    compilers must be able to support up to 12
    dimensions.
  • Lets examine some 2D Arrays.

9
Multi-Subscripted Arrays
  • 2D Arrays are useful for lots of applications
  • Track company stock price for 5 different
    companies over 30 days. (just create a 5 x 30
    array.)
  • Track homework grades for 5 homework assignments
    completed by 55 students (just create a 5 x 55
    array.)

10
Multi-Subscripted Arrays
  • To declare a 1-D Array, we specify 1 size.
  • data_type array_name size
  • To declare a 2-D Array, we specify 2 sizes
  • Examples
  • int a23 / Creates a 2x3 array
  • of ints /
  • double b52 / Creates a 5x2 array
  • of doubles /

data_type array_name of rows of columns
11
Multiple-Subscripted Arrays
  • Multiple subscripts - tables with rows, columns
  • Like matrices specify row, then column.
  • Initialize
  • int b 2 2 1, 2 , 3, 4
  • Initializers grouped by row in braces
  • int b 2 2 1 , 3, 4

Column subscript
 
Array name
Row subscript

12
Multiple-Subscripted Arrays
  • Referenced like normal
  • cout ltlt b 0 1
  • Will output the value of 0
  • Cannot reference with commas
  • cout ltlt b( 0, 1 )
  • Will try to call function b, causing a syntax
    error

13
(No Transcript)
14
(No Transcript)
15
(No Transcript)
16

The array is 0 1 2
3 studentGrades0 77 68 86
73 studentGrades1 96 87 89
78 studentGrades2 70 90 86 81   Lowest
grade 68 Highest grade 96 The average grade for
student 0 is 76.00 The average grade for student
1 is 87.50 The average grade for student 2 is
81.75
17
Strings in C
  • Yeah, well, there arent any. Sorta.
  • As you may have already seen, C Style Strings are
    simply null terminated Character arrays. This is
    probably not the greatest way to do it.
  • C Style Strings use the STL (Standard Template
    Library) to store strings. This is a better way.
    Im going to teach both.

18
Strings in C
  • I know what youre thinking.
  • Wake me up when we get to the C style. Bad
    idea.
  • But why do I have to learn old style Strings??
  • I can think of at least 4 reasons

19
Why learn the old style Strings?
  • If you need to maintain any legacy C code, you
    will encounter C-style strings. Some programmers
    do use them.
  • The string class was not part of the library of
    early versions of C, so other libraries still
    use the C-style Strings.
  • It is used in C to handle command line
    arguments.
  • Your lab manual uses them ?

20
Strings in C
  • Exampes
  • char s1 "example"
  • char s220 "another example
  • would store the two strings as follows
  • s1 example\0
  • s2 another example\0????
  • In the first case the array would be allocated
    space for eight characters, that is space for the
    seven characters of the string and the null
    character. In the second case the string is set
    by the declaration to be twenty characters long
    but only sixteen of these characters are set,
    i.e. the fifteen characters of the string and the
    null character. Note that the length of a string
    does not include the terminating null character.

21
So why are these bad?
  • A character array of sufficient size must be
    defined or allocated to hold the string. The
    array must be at least the length of the string
    plus one. One byte is needed to hold the null
    terminator. It is the programmer's responsibility
    to be certain that the array is large enough. The
    compile will not issue any warnings or errors if
    they size is too small. Errors in array size will
    result in run-time errors. The program may crash,
    behave erratically or operate incorrectly.
  • At times, it is necessary to explicitly add the
    null terminator.
  • Pointers are commonly needed and used to access
    and manipulate the string data.
  • When copying strings, the programmer must check
    that the destination array is large enough. When
    adding to strings, again, the array size must be
    considered

22
Manipulating Strings
  • To manipulate C-styles strings in C, you need
    to call library functions to do it
  • First, include the ltcstringgt library
  • include ltcstringgt
  • Then, you call the various library functions
  • Example
  • strcpy(dest_str,source_str) // copies
    source_str into // dest_str

23
String Functions
  • Listed on Page 363 of the book.
  • A few examples..
  • strcpystrcpy copies a string, including the null
    character terminator from the source string to
    the destination. This function returns a pointer
    to the destination string, or a NULL pointer on
    error. Its prototype ischar strcpy(char dst,
    const char src)

24
String functions
  • strncpystrncpy is similar to strcpy, but it
    allows the number of characters to be copied to
    be specified. If the source is shorter than the
    destination, than the destination is padded with
    null characters up to the length specified. This
    function returns a pointer to the destination
    string, or a NULL pointer on error. Its prototype
    ischar strncpy(char dst, const char src,
    size_t len)strcatThis function appends a
    source string to the end of a destination string.
    This function returns a pointer to the
    destination string, or a NULL pointer on error.
    Its prototype ischar strcat(char dst, const
    char src)

25
STL string class
  • String ClassThe C Standard Library provides a
    string class. To use this class you must include
    the string include file in your
    program.include ltstringgt
  • Unlike C-style strings, the internal
    representation of the string data is hidden by
    the string class. The data is set, accessed and
    manipulated using the methods of the string
    class. The programmer need not be concerned with
    how or where the string is stored. This is an
    example of encapsulation.

26
STL string class
  • include ltiostreamgtinclude ltstringgtusing
    namespace stdint main()    string S1 //
    Default constructor, no initialization    string
    S2("Hello") // Initialization with a C-Style
    string    string S3("Hello from About") //
    Initialization with a C-Style string    string
    S4(S3)  // Initialization with another string
    object    cout ltlt "S2 " ltlt S2 ltlt
    endl    cout ltlt "S3 " ltlt S3 ltlt endl   
  •   S1 S2 // Assignment of one string
    to another    cout ltlt "S1 " ltlt S1 ltlt endl

27
STL string class
  • String OperationsThe string class supports
    relational operators, such as lt, lt, , !, gt
    and gt for comparing strings.
  • The "" operator is used for string
    concatentation.
  • The subscript operator, , can be used to access
    or set individual elements of a string.

28
STL string class
  • The string class also has methods empty(), to
    test for empty strings, and size(), to return the
    string length.
  • The string class also has a method called
    c_str(), which returns a C-style string, for
    backwards compatiblity.

29
STL string class
  • include ltiostreamgtinclude ltstringgtusing
    namespace stdint main()     string
    S1    string S2("from ")    string
    S3("About")    string S4
  •    if (S1.empty())            cout ltlt "S1
    is empty" ltlt endl        cout ltlt "It has length
    " ltlt S1.size() ltlt endl        else
            cout ltlt "No it's not" ltlt endl    

30
STL string class
  •     S1 "Hello "    cout ltlt "S1 now has
    length " ltlt S1.size() ltlt endl    if (S3 lt
    S1)    // Relational Comparison            cout
    ltlt "A comes before C" ltlt endl        S4
    S1 S2 S3   // Concatenation    cout ltlt
    "S4 " ltlt S4 ltlt endl    S1 S2    //
    Concatenation    S1 S3    cout ltlt "S1 "
    ltlt S1 ltlt endl   

31
STL string class
  •      //Subscripting    cout ltlt "S10 " ltlt S10
    ltlt endl    cout ltlt "S11 " ltlt S11 ltlt
    endl    cout ltlt "S12 " ltlt S12 ltlt
    endl    cout ltlt "S13 " ltlt S13 ltlt
    endl    cout ltlt "S14 " ltlt S14 ltlt
    endl    cout ltlt "S15 " ltlt S15 ltlt
    endl    return 0

32
STL string
Write a Comment
User Comments (0)
About PowerShow.com