C++ STL入门代码

/********************************************//**
 * The author: yTOc
 * Algorithm : STL中vector的构造
 * The date : 2014-10-09 23:11:37
 ***********************************************/

#include <cstring>
#include <iostream>
#include <vector>

using namespace std;

int arry[10] = {12, 45, 123123, 64, 12, 22, 63, 23, 12, 55};
char str[20] = "Hello World!";

int main()
{

    vector<int> vec1(arry, arry+10);///< 首元素是ar, 尾元素是ar+9, 不包括ar+10
    vector<char> vec2(str, str+strlen(str));///< 理解同上
    cout << "vec1 : " << endl;
    for(vector<int> :: const_iterator p = vec1.begin(); p != vec1.end(); p++)
        cout << *p << " ";
    cout << '\n' << "vec2 : " << endl;
    for(vector<char> :: const_iterator p = vec2.begin(); p != vec2.end(); p++)
        cout << *p;
    cout << endl;
    return 0;
}
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;

typedef vector<int> INTVECTOR;///< 自定义类型

int main()
{
    INTVECTOR vec1;///< vec1对象初始为空
    INTVECTOR vec2(10, 6);///< 最初有十个值为6的元素
    INTVECTOR vec3(vec2.begin(), vec2.begin()+3);///< 最初有三个值为6的元素(属于拷贝构造)
    INTVECTOR :: iterator i;///< 声明一个名为i的双向迭代器
    cout << "vec1.begin() -- vec1.end() : " << endl;
    for(i = vec1.begin(); i != vec1.end(); i++)///< 显示vec1中的数据
        cout << *i << " ";
    cout << endl;
    cout << "vec2.begin() -- vec2.end() : " << endl;
    for(i = vec2.begin(); i != vec2.end(); i++)///< 显示vec2中的数据
        cout << *i << " ";
    cout << endl;
    cout << "vec3.begin() -- vec2.end() : " << endl;
    for(i = vec3.begin(); i != vec3.end(); i++)
        cout << *i << " ";
    cout << endl;

    ///< 测试添加和插入函数

    vec1.push_back(2); ///< 从容器后面添加一个元素成员
    vec1.push_back(4);

    vec1.insert(vec1.begin()+1, 5);///< 在vec1第一个位置上插入成员5
    vec1.insert(vec1.begin()+1, vec3.begin(), vec3.end());///< 在vec1第一个位置上插入vec3的所有成员


    cout << "after push() and insert() now the vec1 is : " << endl;
    for(i = vec1.begin(); i != vec1.end(); i++)
        cout << *i << " ";
    cout << endl;

    vec2.assign(8, 1);///< 8个成员的初始值为1

    cout << vec1.front() << endl;
    cout << vec1.at(4) << endl;
    cout << vec1[4] << endl;

    vec1.pop_back();///< 最后一个成员移除
    vec1.erase(vec1.begin()+1, vec1.end()-2);

    cout << vec1.size() << endl;
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值