📐

Defining and Initializing Vectors

Jul 17, 2024

Defining and Initializing Vectors

Introduction

  • Discussion continuation on vectors.
  • Focus on defining and initializing vectors.

Default Initialization

  • Creates an empty vector of a specified type.
  • Syntax: vector<Type> vectorName;
  • Example: vector<string> svec;
    • Initializes an empty string vector named svec.

Copying Elements from Another Vector

  • Creating a vector by copying elements from an existing vector.
  • Syntax: vector<Type> newVector(existingVector); or vector<Type> newVector = existingVector;
  • Example: vector<int> myvec = {1, 2, 3}; vector<int> newvec(myvec); vector<int> newvec1 = myvec;
    • newvec and newvec1 will both contain elements {1, 2, 3}.
  • Type mismatch error if the types do not match: vector<string> svec = myvec; // Error
    • svec (string) ≠ myvec (integer).

List Initializing a Vector

  • Creating a vector with zero or more initial values using curly braces {}.
  • Syntax: vector<Type> vectorName = {val1, val2, ...}; or vector<Type> vectorName{val1, val2, ...};
  • Example: vector<string> colors = {"red", "green", "blue"};
  • Common mistake with parentheses (): vector<string> colors("red", "green", "blue"); // Error

Specifying Number of Elements

  • Creating a vector with a specified number of elements, optionally with default values.
  • Syntax: vector<Type> vectorName(size, value); vector<Type> vectorName(size);
  • Examples: vector<int> myvec(5, -2); // Five elements, all -2 vector<string> svec(6, "egg"); // Six elements, all "egg" vector<int> ivec(12); // Twelve elements, default 0

Differences in Bracket Types

  • Example variations using parentheses () vs curly braces {}.
  • Examples: vector<int> v1(5); // Five elements, default 0 vector<int> v2{5}; // One element, value 5 vector<int> v3(5, 2); // Five elements, all value 2 vector<int> v4{5, 2}; // Two elements, values 5 and 2 vector<string> v5{"cup"}; // One element, "cup" vector<string> v6("cup"); // Error: invalid syntax vector<string> v7{10}; // Ten default-initialized elements; tricky vector<string> v8{10, "cup"};// Ten elements, all "cup"
  • Importance of correct bracket usage to avoid errors or different initializations.

Conclusion

  • Reviewed various ways to define and initialize vectors.
  • Importance of paying attention to bracket types for correct vector initializations.