Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          vectors/vector-2-cpp11.cc - Another vector example - constructors, insertion, lexicographic comparison.Lecture 3 - slide 14 : 27
Program 4

// Another vector example - constructors, iterators, insertion, lexicographic comparison.

#include <iostream>
#include <string>
#include <vector>

using std::string;
using std::vector;
using std::cout; using std::endl;

void print_vector(string name, vector<string> &sv);

int main(){
  // Vector constructing - C++11:
  vector<string>
     sv1{},              // An empty vector of strings
     sv2{10},            // A vector of 10 empty strings
     sv3{5, "AP"},       // A vector of 5 strings each "AP"
     sv4{4, "KN"},       // A vector of 4 strings each "KN"
     sv5{sv3.begin(), sv3.begin() + 3},
                         // A vector copied from front of sv3
     sv6{"1", "2", "3"}; // List initialization: Three strings.

  // Size and capacity:
  cout << "sv6.size(): "     << sv6.size()     << endl;  // 3
  cout << "sv6.capacity(): " << sv6.capacity() << endl;  // 3

  // Change every second element of sv3 to "PA":
  for (vector<string>::iterator iter = sv3.begin();
       iter < sv3.end();
       iter += 2){
    (*iter) = "PA";
  }  

  print_vector("sv3", sv3);

  // Insert 3 elements from sv4 near the end of sv3:
  sv3.insert(sv3.end()-1, sv4.begin(), sv4.begin()+3);

  print_vector("sv3", sv3);

  print_vector("sv4", sv4);   print_vector("sv5", sv5);

  // Lexicograhpic comparison between sw4 and sw5:
  if (sv4 == sv5)
    cout << "sv4 is equal to sv5" << endl;
  else if (sv4 < sv5)
    cout << "sv4 is less than sv5" << endl;
  else 
    cout << "sv4 is greater than sv5" << endl;
}

void print_vector(string name, vector<string> &sv){
   cout << name << ":" << endl;
   for (vector<string>::iterator iter = sv.begin();
       iter != sv.end();
       iter++)
     cout << "  " << (*iter) << endl;
   cout << endl;
}