[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci201] / 18
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] <18> [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Sun Mar 15 10:44:36 PDT 2009

Contents


    18 Arrays

    Previous -- Vectors

    [ 17.html ]

    Prepare

      7.1 Introduction

      7.2 Arrays

      7.3 Declaring Arrays

      Notice the syntax.

      7.4 Examples Using Arrays

        7.4.1 Declaring an Array and Using a Loop to Initialize the Array’s Elements

        Notice the syntax for declarations.

        Notice how arrays and for loops fit together

        7.4.2 Initializing an Array in a Declaration with an Initializer List

        Powerful.

        7.4.3 Specifying an Array’s Size with a Constant Variable and Setting Array Elements with Calculations

        THis is the best practice with array -- seeing they have a fixed size: give it a name andt tell the compiler that it is a constant (const). Do it.

        7.4.4 Summing the Elements of an Array

        A classic technique -- use it.

        7.4.5 Using Bar Charts to Display Array Data Graphically

        A classic technique -- use it.

        7.4.6 Using the Elements of an Array as Counters

        A classic technique -- use it.

        7.4.7 Using Arrays to Summarize Survey Results

        A classic technique -- use it.

        7.4.8 Using Character Arrays to Store and Manipulate Strings

        The original technique: be very careful with this. Nothing is quite what it seems.

        Skip 7.4.9 Static Local Arrays and Automatic Local Arrays

      . . . . . . . . . ( end of section 7.4 Examples Using Arrays) <<Contents | End>>

    . . . . . . . . . ( end of section Prepare) <<Contents | End>>

    Deliver a Question and P9

    Exercises

    Given some vector declarations -- translate them into array declarations.

    Questions and Answers

      What is a data structure

      Any organized collection of data -- all objects, arrays, vectors, lists, maps, sets, .... and so on a classic data structures.

      Can you create an if statement with a vector

      You can use vectors inside the conditions in vectors, because you can use the accessors and subscripts to get normal values and test those. Similary you can use vectors inside the body of an if-statement.... just as if it was outside. And you can declare a local vector.... just like you declare any other local variable...

      Are than any more Accessor for vectors other than empty, size, front, and back

      Just subscript and at.

      What happens if vector elements are not around square brackets

      You have got into a separate universe, or you will get compile errors.

      Can an element of a vector, other than the last element by removed

      Not efficiently. The does exist an "erase" function which will in fact overwrite the existing elements and pop the last one.

      If you really need to insert and erase elements in a vector.... you should be using a <list>.

      How to vectors and arrays relate to each other

      Arrays are a lot more primitive and vectors. They do share a common notation for subscripts. Arrays are OK when you know how many elements you need and you don't want to do anything clever with them.

      Is there anything I can do with an array that I can't do with a vector

      I know of onw thing that I can do with an array, but not with a vector -- use an initializer list. This means that
      	int fib[] = {1,1,2,3,5,8,13};
      is OK but
      	vector <int> fib = {1,1,2,3,5,8,13};
      does not compile it complains about not being given a sigle value for the vector. There are three obvious ways round this. (1) use an array (when it doesn't grow). (2) Push the data directly into an empty vector. [ initializeVector.cpp ] Or (3) Put the data in an array with an initializer and then push it into the vector: [ initializeArrayFirst.cpp ]

      With objects something similar works [ vectorOfObjects.cpp ] for example.

      Can I change the size of an array by ....

      No. No. Nothing will change the size of a local array once it is declared.

      Why can I go outside the bounds of an arrray

      Because a compiled program doesn't see the boundaries. It knows the start of arrays, but not where they end. It has no way of calculating how far you can go.

      A running program sees data as a gigantic array of words with the beginning of the data for each variable is known...

      What happens if I go off the end of an array

      You overwrite the adjacent memory. It may crash the program or the computer. But usually you start to get very weird answers for no apparent reason.

      What about walking off the end of an array with a for loop

      The results are unpredictable and never good.

      What about vectors -- can you go off the end without errors

      Yes. But the results are wrong, weird, and crash software.

      What is a Smart Array

      It knows how big the array is. It looks very like an array but any attempt to go ouside it is trapped as an error. It is a safe array.... but may be slower than a raw array. One of the neater things about C++ is that you can create a class that hides its data and define the meaning of the subscript operator ([]) for objects in the class, so you can use a smart array just like a dumb one!

      What happens if someone inputs too much data into an array

      In the worst case scenario they can insert there data into your program where it will be executed. This is called "A buffer overrun attack". It is most often caused by using "gets" or "cin>>" into an array.

      Does getline(cin, SIZE, ENDCHAR) help avoid buffer over runs

      Yes.... except that you have problems when SIZE characters are read. You have to input the rest of the line after the SIZE characters. I think it even fails to terminate the array with a '\0' or something like that.

      Please use strings for unknown ammounts of data. Or read it in one character at a time...

      Can memory be reserved for several arrays with many decalarations

      Yes.

      How many different types of arrays

      Infinity. One for each type of data at least.

      What happens if people supply too much data in an intializer

      I think you get a compile error .... I hope so.

      How to avoid supplying too much data in an initializer

      Let the compiler count the elements for you
       		double s[] = {1.23, 3.45, 5.67,7.89};

      Can you initialize arrays in any part of a program

      You can initialize an array only in a daclation of a local variables. So any where where a local declaration is legal can have an array and an initializer.

      You can not initialize a data memebr/dtat field in a class... even if it is an array.

      Is using an initializer fast than a for loop

      Yes. The compiler does the initializaitiopn before the program starts, I believe.

      Why is it better to store characters in char arrays rather than string

      There are only two reasons: speed and because we are forced to. Arrays are a bit faster because they have no frills and no safety features -- just like a sports car.

      We are forced to use a character array each time we type in a string literal with double quotes:

       		"Hello"

      This is converted into an unamed array of 6 characters (notice the 6(six) chars) initialized to

       		char noname[]={'H', 'e', 'l', 'l', 'o', '\0'};
      Notice the extra NULL character at the end.

      Personally -- I use STL <string>s as much as I possible can. They may be slower but they are less confusing, more powerful, and safer.

      Which feature of character arrays is mostly used

      Their is a CSCI202 technique known as a "char*" (pronoounced "char star") that gives you tight, elegant, and fast code for many operations. They also tend to be surprisingly buggy.

      Can we us const to declare a function

      First, you can declare parameters in a function to be constant
       		type function (...., const Type parameter, ...)...

      Secod you can attach "const" to a member function of a class to tell the compiler that it is an accessor -- a function that does not change its object (examples for vectors: size() and empty()). You do it like this inside a class

       	class Sample
       	{
       		...
       		double mean () const;
       		...
       	};
      or outside the class
       	type Sample::mean()const { return sum()/size(); }

      But I don't think you can define a "const function" -- it doesn't mean anything.

      Why do we need static_cast, why not write the expression so that it is in the right type

      It is often possible to write expressions so that the give data of the right type. For example
       		1/2
      uses int arithmetic to calculate 0. But
       		1.0/2
      will use double arithmetic to calculate 0.5.

      However, if you have to integers, i and j, and need their ratio

       		i/j
      gives a rounded int answer... A trick is to include a double:
       		(1.0*i)/j
      for example. And form the 1970's to the 1990's we could cast a number like this
       		((double)i)/j
      or, later,
       		double(i)/j
      however after 2000 the standard promotes the explicit static cast
       		static_cast<double>(i)/j
      which may be longer but is quite clear as to what you need to do.

      Whay sort and serach since this is inefficient

      Because people need the operations. They need to search for data -- think Google! And search can go faster if the data is in the right order.

      People also like to see data in different orders.... and each order means you have to sort the data into that order.

      Besides the algorithms are interesting and fun.

    Quiz 8 -- Vectors

    Next -- Wind up arrays

    [ 19.html ]

    Abbreviations

  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. Function::programming=A selfcontained and named piece of program that knows how to do something.
  3. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  4. KDE::="Kommon Desktop Environment".
  5. OOP::="Object-Oriented Programming", Current paradigm for programming.
  6. Semantics::=Rules determining the meaning of correct statements in a language.
  7. SP::="Structured Programming", a previous paradigm for programming.
  8. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  9. Q::software="A program I wrote to make software easier to develop",
  10. TBA::="To Be Announced", something I should do.
  11. TBD::="To Be Done", something you have to do.
  12. UML::="Unified Modeling Language".
  13. void::C++Keyword="Indicates a function that has no return".

End