2014年2月25日 星期二

Array to vector

#include <iostream>
#include <vector>
using namespace std;

int main(){
    const  int size_array = 4;
    int a[size_array] = {1,2,3,4};
    int *p = a;
    int *q = a + size_array;

    int *c = p;
    while( c != q ){
        cout << *c << " ";
        c++;
    }
    cout << endl;

    vector<int> vec(p, q);
    vector<int>::iterator i = vec.begin( );
    while( i != vec.end() )
    {
        cout << *(i++) << " ";
    }
    cout << endl;

    vector<int> vec2;
    vec2.assign(p, q);
    i = vec2.begin( );
    while( i != vec2.end() )
    {
        cout << *(i++) << " ";
    }

    return 0;
}

int *q = a + size_array;
This is an off-the-end pointer

vector<int> vec(p, q);
Create a vector and use an array to initialize the elements by passing the begin pointer and off-the-end pointer

vector<int> vec2;
vec2.assign(p, q);
Create an empty vector, then using the assign function to assign the elements in an array to it
( Note: if the assign function is used, then the old contents will be wiped out, and replaced by the new contents, meanwhile, the size will be changed )



沒有留言:

張貼留言