[cpp] Vector

3 篇文章 0 订阅
2 篇文章 0 订阅

vector是一种类模板,它表示对象的集合。当对象个数不定时用vector

包含

vector的使用需要包含适当的头文件:

#include<vector>
using std::vector;

直接初始化

和其他类型初始化方式类似

vector <T> v1
vector <T> v2(v1)       //vector<T> v2 = v1
vector <T> v3(n, v1)    //vector<T> v3(n)
vector <T> v4{a,b,c,...}//vector <T> v5 = {a,b,c,...}

vector方法

.push_back

向vector的末端加入值
Eg:

#include <iostream>
#include <vector>

int main()
{
    // 创建含有整数的 vector
    std::vector<int> v = {7, 5, 16, 8};

    // 添加二个整数到 vector
    v.push_back(25);
    v.push_back(13);

    // 迭代并打印 vector 的值
    for(int n : v) {
        std::cout << n << ' ';
    }
    std::cout << endl;

}

g++ -o out prog_vector.cpp -std=c++11

引用操作


#include<iostream>
#include<vector>
using namespace std;
int main()
{

    vector<int> v_int;

    for(int i = 0; i < 10; i++)
    {
        v_int.push_back(i);
    }

    for(auto &i: v_int)
    {
        i *= i;
    }
    // cout << v_int.size() << endl;
    for(int i : v_int)
    {
        cout << i << ' ';
    }

    cout << endl;
    return 0;
}

迭代器

for(auto i = v_int.begin(); i != v_int.end(); i++)
{
    cout << *i << " ";
}
cout << endl;

到这里,可以直接理解vector为C里面用void*写的链表,封装起来方便重写代码,但也增加了开销。

其它

practice 3.17


#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
    vector<string> v_str;

    string str;

    while(cin >> str)
    {
        for(auto &c : str)
            c = toupper(c);

        v_str.push_back(str);
    }

    for(auto i : v_str)
        cout << i << endl;

    return 0;
}

practice 3.20

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int>  vi;
    int i;

    while(cin >> i)
    {
        vi.push_back(i);
    }
    for(auto b = vi.begin(), e = vi.end()-1, 
    mid = b + (e-b)/2, j = b; j != mid; j++, e--)
    {
        cout << (*j) + (*e) << ' ';
    }
    cout << endl;

    return 0;
}

more

更多内容请参考 参考链接

reference

cpp primer
http://zh.cppreference.com/w/cpp/container/vector
http://www.cplusplus.com/reference/vector/vector

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值