6: Vectors
40 Questions
2 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What does the line 'std::vector crossed_out = std::vector(n, false);' do?

  • Creates a vector of Booleans initialized to false. (correct)
  • Creates a vector of Booleans initialized to true.
  • Creates a vector of characters initialized to empty.
  • Creates a vector of integers initialized to zero.
  • The part 'for (int i=0; i < n; i++)' indicates that the loop will iterate n times.

    True

    What is the primary purpose of a vector in programming?

    To store a dynamically sized collection of elements.

    In C++, a vector is part of the ________ Library.

    <p>Standard Template</p> Signup and view all the answers

    Match the following vector operations with their descriptions:

    <p>Push_back = Adds an element to the end of the vector Pop_back = Removes the last element of the vector Size = Returns the number of elements in the vector Clear = Removes all elements from the vector</p> Signup and view all the answers

    What does a precondition define in the context of a function?

    <p>What is required to hold when the function is called</p> Signup and view all the answers

    The postcondition specifies what is required to be true before the function is called.

    <p>False</p> Signup and view all the answers

    What happens if a function is called with invalid preconditions?

    <p>Undefined behavior</p> Signup and view all the answers

    The function 'pow' has a postcondition that guarantees the return value is ___ when the precondition is met.

    <p>b^e</p> Signup and view all the answers

    Which of the following is a recommended practice for defining preconditions?

    <p>Ensure the precondition is as weak as possible</p> Signup and view all the answers

    Match the following terms with their definitions:

    <p>Precondition = Requirements before function call Postcondition = Guaranteed outcomes after function call Undefined behavior = Results of invalid preconditions Overflow = Exceeding the limits of data representation</p> Signup and view all the answers

    Weak postconditions provide the most detailed information available regarding a function's effects.

    <p>False</p> Signup and view all the answers

    What should you document to help understand the function's behavior under its preconditions?

    <p>Document the function's expected behavior and limitations.</p> Signup and view all the answers

    If a function is called with preconditions not met, it may lead to ________ behavior.

    <p>undefined</p> Signup and view all the answers

    What is the primary goal when defining preconditions and postconditions for functions?

    <p>To document expectations and maintain reasonable limits</p> Signup and view all the answers

    What is the consequence of using an assert statement with a false expression?

    <p>It halts the program with an error message.</p> Signup and view all the answers

    Preconditions are always checked using assert statements.

    <p>False</p> Signup and view all the answers

    What are the postconditions in the root function example?

    <p>The result should return the larger root of the polynomial x^2 + p x + q.</p> Signup and view all the answers

    The expression used in an assert statement must be convertible to ______.

    <p>bool</p> Signup and view all the answers

    Match the type of assertion with its purpose:

    <p>Precondition = Checks validity before computation starts Postcondition = Checks correctness after computation finishes Invariant = Checks properties throughout method execution</p> Signup and view all the answers

    What is the purpose of using assert statements in function 'pow'?

    <p>To ensure the precondition holds when the function is called.</p> Signup and view all the answers

    In the gcd function example, the assertion 'assert(x > 0 && y > 0);' confirms that both inputs are non-negative.

    <p>False</p> Signup and view all the answers

    Why is stepwise refinement important in programming?

    <p>It simplifies problem-solving by breaking problems into smaller, manageable parts.</p> Signup and view all the answers

    Using assertions helps to enforce ______ during program execution.

    <p>correctness</p> Signup and view all the answers

    Match the programming concept with its definition:

    <p>Preconditions = Requirements that must be true before a function is executed Postconditions = Requirements that must be true after a function is executed Assertions = Statements that check conditions during runtime</p> Signup and view all the answers

    What is the first step in the process of stepwise refinement?

    <p>Create a coarse solution</p> Signup and view all the answers

    The refinement process only focuses on coding functions without considering data representation.

    <p>False</p> Signup and view all the answers

    What is the purpose of stepwise refinement in programming?

    <p>To break down a problem into smaller, manageable parts sequentially.</p> Signup and view all the answers

    In the example problem, the rectangles are defined by their top-left corner coordinates and ______.

    <p>dimensions</p> Signup and view all the answers

    Match the rectangles with their respective properties:

    <p>(x1, y1, w1, h1) = First rectangle with top-left corner at (x1, y1) (x2, y2, w2, h2) = Second rectangle with top-left corner at (x2, y2) w1 = Width of the first rectangle h2 = Height of the second rectangle</p> Signup and view all the answers

    What is a critical factor to check when determining if two rectangles overlap?

    <p>The position and dimensions of both rectangles</p> Signup and view all the answers

    The refinement process leads to the development of partial solutions that can be used in other problems.

    <p>True</p> Signup and view all the answers

    In the main function of the coarse solution, what are the two main actions captured?

    <p>Input rectangles and output the solution on overlap.</p> Signup and view all the answers

    Width and height inputs for the rectangles may be ______.

    <p>negative</p> Signup and view all the answers

    Which of the following is NOT a step in the refinement process?

    <p>Finalizing the program</p> Signup and view all the answers

    What is true about function declarations in programming?

    <p>A function can only be used after its declaration in the code.</p> Signup and view all the answers

    A function's definition is never considered a declaration.

    <p>False</p> Signup and view all the answers

    What must be true about the lines of code that follow a function declaration?

    <p>They can use the function that has been declared.</p> Signup and view all the answers

    The statement 'void B (int i);' is an example of a ___ declaration.

    <p>separate</p> Signup and view all the answers

    Match the following terms with their definitions regarding functions:

    <p>Declaration = A statement that introduces a function's name and type Definition = A statement that includes the body of the function and implementation Precondition = A condition that must be true before a function is executed Postcondition = A condition that must be true after a function is executed</p> Signup and view all the answers

    Study Notes

    Introduction to Computer Science

    • Course details: 252-0032, 252-0047, 252-0058
    • Authors: Manuela Fischer and Felix Friedrich
    • Department: Department of Computer Science, ETH Zurich
    • Semester: Fall 2024

    Vectors

    • Vectors store sequences of homogeneous data.
    • Iteration over numbers: for (int i=0; i<n; ++i) {...}
    • Sieve of Erathostenes example: calculates prime numbers less than n.
    • Crossing out non-prime numbers using a boolean vector.
    • Vector type: std::vector<T> where T is the element type.
    • Vector initialization: std::vector<T>(n,e) where n is the number of elements and e is the initial value for each element. Other initialization methods (e.g., initializer lists) are possible.
    • Element access: [] index operator, used for reading and writing elements.
    • std::vector<int> v = std::vector<int>(10); std::cout << v.at(10); example shows accessing elements using .at(), which performs bounds checking at runtime. Using [] might cause undefined behavior if referencing outside container bounds.
    • Vectors can be initialized with different values (e.g., 0, 2, a direct list of values).

    Memory Layout and Properties

    • Vectors store elements in contiguous memory.
    • Random access is efficient.

    Nested Vectors (Vectors of Vectors)

    • Used to represent multidimensional structures like tables or matrices.
    • Can be initialized using initialization lists or filling with a specific size and default value.
    • Access elements using nested indexing: m[i][j] for row i and column j.
    • Memory storage is flat, row-by-row.
    • Example to compute sum of lower triangle of a square matrix using nested for loops.

    Beware of Mixed Integer Expressions

    • Vector functions often use unsigned integers (e.g., v.size()).
    • Mixed integer expressions can lead to unexpected behavior (e.g., infinite loops due to unsigned arithmetic—common error).
    • Compiler warnings can help detect potential issues. Example for (int x = 0; a.size()-x-1 >= 0; ++x){ std::cout << x; } demonstrates an infinite loop (due to the unsigned nature of a.size() ).

    Reference Types

    • Pass by reference: Parameter receives the address of the actual argument, allowing modifications to be reflected in the caller.
    • Pass by value: Parameter receives a copy of the actual argument, modifications do not affect the original argument.
    • Reference types are denoted by T& (e.g., int&, std::vector<double>&).
    • Reference variables act as aliases to the objects they reference. References must have an existing object to reference.
    • Return by reference: Function returns a reference, allowing modifications to the original argument directly. Use of reference return type leads to changes to the original object, like int& inc(int i) example.
    • Temporary objects: A reference to a temporary object can lead to undefined behavior. A reference must remain valid for the lifetime of the object it refers to. Example: int& foo(int i) { return i; }.

    Const References (const T& )

    • Passing elements by constant reference (const T&): Prevents accidental modification of the passed object within the function, while still avoiding unnecessary copying of large objects.
    • Improves performance by avoiding unnecessary copying (especially for large objects). Example of computing vector average using const std::vector<double>& values which prevents modification.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Lecture 6: Functions II PDF

    Description

    This quiz focuses on the concept of vectors in computer science, covering their storage, iteration, and properties. It includes examples such as the Sieve of Eratosthenes and illustrates the use of nested vectors. Test your understanding of how vectors function and their application in programming.

    More Like This

    Vector Quiz
    5 questions

    Vector Quiz

    EffusiveHeliotrope avatar
    EffusiveHeliotrope
    Ransomware Attack Vectors
    1 questions

    Ransomware Attack Vectors

    FlawlessPennywhistle avatar
    FlawlessPennywhistle
    Chapter 6: Vectors Flashcards
    15 questions
    Use Quizgecko on...
    Browser
    Browser