Arrays and Vectors

Mattox Beckman

Objectives

  • Be able to describe the differences between C-style arrays and Vectors
  • Use built-in methods to manipulate C++ Vectors

C-Style Arrays

  • A C-style array is simply a block of contiguous memory.
  • First element is always 0.
  • Note the < in the for loop. If you put <= you will certainly have touble!
    • If you get a “runtime error” from the judge, check for that.
  • Access an element by index with brackets: \({\cal O}(1)\) time. Very fast!
    • If you have to “look for” an element, it’s \({\cal O}(n)\) time. Use with caution.
int arr[100];
int i;

for(i=0; i<100; ++i) {
   arr[i] = i * 10;
 }

C-Style Arrays, initialization

  • You can initialize arrays inline in C if you need to.
  • Note that uninitialized items are undefined!
    • You don’t have to initialize right away, but you have to before you use it!
int foo[10] = {8,6,7,5,3,0,9};
char suits[4] = "SHCD"; // Spades, Hearts, Clubs, Diamonds

Vectors

  • Vectors in C++ are awesome. Use them unless you have good reason not to.
    • They can grow dynamically! No need to determine the proper size in advance.
    • Many iterators to provide traversals.
    • Reasonable default initialization.
    • Use push_back to insert an element at the end.
      • Inserting at the beginning is slow! Don’t do it!
vector<int> foo;

for(int i=0; i<N; ++i) {
 cin >> data;
 foo.push_back(data);
}

Vector initializations

  • The constructor can initialize the vector for you.
    • One argument \(n\): \(n\) instances of the default.
    • Two arguments \(n\) and \(x\): \(n\) copies of \(x\).
vector<int> foo(100);
vector<int> foo(500,123);
  • You can use foo.reserve(1000) to pre-allocate space.

Looping

  • C Style
int sum=0;
for(i = 0; i<foo.size(); ++i)
  sum += foo[i]:
  • Iterator Style
int sum=0;
for(auto i = foo.begin(); i != foo.end(); ++i)
  sum += *i;
  • Reverse Iterator Style
int sum=0;
for(auto i = foo.rbegin(); i != foo.rend(); ++i)
  sum += *i;

Style

  • Certain types come up a lot, so some standard typedefs have evolved:
typedef vector<int> vi;
typedef vector<vi> vvi;

Pairs

  • It is often convenient to define tuples as well.
pair<int,int> coord;

coord.first = 10;
coord.second = 999;
  • We have standard typedefs for them too.
typedef pair<int,int> ii;
typedef vector<ii> vii;