Monday, April 14, 2014

Vector

// inserting into a vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (3,100);
  std::vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 );

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin();

  std::vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());

  int myarray [] = { 501,502,503 };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

http://www.cplusplus.com/reference/vector/vector/insert/



Two Dimensional Vector

This tutorial will show you how to create a vector matrix, much like an array matrix, for storing data in a two dimensional format. An knowledge of arrays, vectors, loops, and basic C++ programming is necessary to fully grasp the material covered in this tutorial. If you have dealt in array's for a while, you have probably come across two dimensional arrays (matrix). These arrays are often used for storing information in tables or anything where you would want to have two dimensions for data. Since matrices have been so helpful in arrays, making a two dimensional vector would be even better. However, there are a few tricks to making the two dimensional vector. Declaring a two dimensional vector is similar to declaring an array. To start off, you declare your vector of whatever type you want. Use the following code to declare your vector:
vector<vector <int> > vec;
You might think that you can fill in the vectors right now, much like you would an array matrix, but one more step must be taken. Because there are no dimensions assigned for the vector matrix right now, the rows of the matrix don't actually exist yet. What we have after the code we just typed in is an empty vector that can hold vectors of integers. To create the rows of the vector, we have to use a loop like the following:
for(int i = 0; i < 5; i++)
{
    vector<int> row;
    vec.push_back(row);
}
This statement will fill the vector "vec" with empty vectors that can contain integers. Now, we can use an assignment statement to fill a part of the matrix:
vec[0].push_back(5);
And, as you can see by outputting the part of the matrix that was filled, the data was correctly assigned:
cout << vec[0][0] << endl;
Tada! You have now created a two dimensional vector. This code was written and compiled in Dev-C++ and may need some tweaking to run in other compilers. The source code for this project is attached for convenience. If you would like to offer corrections or contribute to the information presented here, please post a reply.

No comments:

Post a Comment