vector的一点使用

来源:互联网 发布:马云淘宝如何盈利 编辑:程序博客网 时间:2024/04/28 06:37
这里主要是尝试使用了vector的一些基本方法以及将vector作为vector的模版来使用的两种情况,程序也很简单。如下:
(因为使用哪个“插入代码”功能实在等不下去了,就直接粘贴了)
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    vector<int> v;
    for (int i = 0; i<5 ;i++ )
    {
        v.push_back(i);
    }
    // copy the vector to the screen, from first to last.
    copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
    cout<<endl;
    // get the top element of th vector
    int i=v.back();
    cout<<i<<endl;
    // // get the bottom element of th vector
    i=v.front();
    cout<<i<<endl;
    // copy the vector to the screen from last ro first
    copy(v.rbegin(),v.rend(),ostream_iterator<int>(cout," "));
    cout<<endl;
    // get the element at specific place
    cout<<v.at(2)<<endl;

    return 0;
}
该程序运行结果如下:
0 1 2 3 4
4
0
4 3 2 1 0
2

另外一个使用vector作为vector的模版的程序:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
   
    vector<vector<int>> vv;

    vector<int> vi;
    vi.push_back(4);
    vi.push_back(6);
    vv.push_back(vi);

    vector<int> vi1;
    vi1.push_back(1);
    vi1.push_back(2);
    vv.push_back(vi1);

    int c = 0;
    // get the vector's capacity. If using size(), it should be as follows:
    // int s = vv.size();
    // while (c<s) {...}
    // note: "while(c<vv.size) {...}" won't get the last element. After pop_back(), the size() decreases.
    while (c<vv.capacity())
    {
        /* first, get the top element via back(), copy its elements to screen;
         * then pop up it to make the top the next element.
         */
        vector<int> v = vv.back();
        copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
        cout<<endl;
        vv.pop_back();
        c++;
    }
   
    return 0;
}
该程序结果如下:
1 2
4 6

我相信,只要努力学习,总会有收获的。






原创粉丝点击