Using vectors Instead of Arrays to store built-in types, objects, pointers, etc. in a sequence - C++ STL

C++ examples for STL:vector

Description

Using vectors Instead of Arrays to store built-in types, objects, pointers, etc. in a sequence

Demo Code

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

using namespace std;

int main() {//  w  ww  . j av  a2s  .c  om
   vector<int>    intVec;
   vector<string> strVec;

   intVec.push_back(3);
   intVec.push_back(9);
   intVec.push_back(6);

   string s = "this ia A and B";

   strVec.push_back(s);
   s = "A";
   strVec.push_back(s);
   s = "B";
   strVec.push_back(s);

   // You can access them with operator[], just like an array
   for (vector<string>::size_type i = 0; i < intVec.size(); ++i) {
      cout << "intVec[" << i << "] = " << intVec[i] << '\n';
   }

   // Or you can use iterators
   for (vector<string>::iterator p = strVec.begin();
        p != strVec.end(); ++p) {
      cout << *p << '\n';
   }

   try {
      intVec.at(300) = 2;
   }
   catch(out_of_range& e) {
      cerr << "out_of_range: " << e.what() << endl;
   }
}

Result


Related Tutorials