C++ STL 常用 函数 用法

 迭代器(iterator)

  个人理解就是把所有和迭代有关的东西给抽象出来的,不管是数组的下标,指针,for里面的、list里面的、vector里面的,抽象一下变成了iterator

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    for(int i = 0; i < 10; ++i )
    {
        v.push_back(i);
    }
    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}


  求和(<numeric> accumulate)

  accumulate(v.begin(),v.end(),0),把从 v.begin() 开始到 v.end()结束所有的元素加到 0上面去

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main()
{
    vector<int> v;
    for(int i = 0; i < 10; ++i )
    {
        v.push_back(i);
    }
    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;
    cout << accumulate(v.begin(),v.end(),0) << endl;
    return 0;
}


 vector(动态数组)

  vector有内存管理的机制,也就是说对于插入和删除,vector可以动态调整所占用的内存空间。  

  vector相关函数

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    v.push_back(3);  //数组尾部插入3
    v.push_back(2);
    v.push_back(1);
    v.push_back(0);
    cout << " 下标 " << v[3] << endl;
    cout << " 迭代器 " << endl;
    for(vector<int>::iterator i = v.begin();i!= v.end();++i)
    {
        cout << *i << " ";
    }
    cout << endl;
    //在第一个元素之前插入111  insert begin+n是在第n个元素之前插入
    v.insert(v.begin(),111);
    //在最后一个元素之后插入222 insert end + n 是在n个元素之后插入
    v.insert(v.end(),222);

    for(vector<int>::iterator i = v.begin();i!= v.end();++i)
    {
        cout << *i << " ";
    }
    cout << endl;

    vector<int> arr(10);
    for(int i = 0; i < 10; i++)
    {
        arr[i] = i;
    }
    for(vector<int>::iterator i = arr.begin();i!= arr.end();++i)
    {
        cout << *i << " ";
    }
    cout << endl;

    //删除 同insert
    arr.erase(arr.begin());

    for(vector<int>::iterator i = arr.begin();i!= arr.end();++i)
     {
        cout << *i << " " ;
     }
    cout << endl ;

    arr.erase(arr.begin(),arr.begin()+5);

    for(vector<int>::iterator i = arr.begin();i!= arr.end();++i)
    {
        cout << *i << " " ;
    }
    cout << endl ;
    return 0 ;
 }


 数组转置 (<algorithm> reverse)  

reverse(v.begin(),v.end())

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    vector<int> v;
    for(int i = 0; i < 10; ++i)
    {
        v.push_back(i);
    }
    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;

    reverse(v.begin(),v.end());


    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}

<p style="margin: 10px auto; line-height: 19px; font-size: 13px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;"><span style="background-color: rgb(255, 255, 255);"> <strong><span style="color: rgb(128, 0, 0);">排序(<algorithm> sort)</span></strong>
</span></p><p style="margin: 10px auto; line-height: 19px; font-size: 13px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;"><span style="background-color: rgb(255, 255, 255);">  sort(v.begin(),v.end())</span></p><pre name="code" class="cpp">#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

bool Comp(const int &a,const int &b)
{
    return a>b;
}

int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(3);
    v.push_back(2);
    v.push_back(55);
    v.push_back(-1);
    v.push_back(0);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);

    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;

    //默认升序
    sort(v.begin(),v.end());


    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;

    //用降序 需要自定义一个降序函数
    sort(v.begin(),v.end(),Comp);


    for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

 字符串(<string>)

  输入

#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

int main()
{
    string s1;
    s1 = "hello";

    string s2;
    char s[1024];
    //scanf 输入速度比cin快的多
    //scanf 是C函数,不可以输入string
    scanf("%s",s);
    s2 = s;

    cout << s1 << endl;
    cout << s2 << endl;

    return 0;
}


 

 尾部添加字符字符串直接用+号 例如: s += 'a'; s += "abc",或者使用append方法,s.append(“123”)

  删除 (erase clear)

  s.erase(it + 1,it + 4); clear()

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s;
    s = "0123456789";
    cout << s << endl;

    string::iterator it = s.begin();

    //删除s[3]
    s.erase(it+3);
    cout << s << endl;

    //删除s[1]~s[3]
    s = "0123456789";
    s.erase(it + 1,it + 4);
    cout << s << endl;

    //全部删除
    s.clear();
    cout << "clear : " << s << endl;

    return 0;
}


 查找(find)

  用find找到string里面第一个要找到元素(char或者串),找到返回数组下标,找不到返回end()迭代器

  string和vector有很多相同的东西,比如length(),size(),empty(),reverse(),相对也容易,就不一一说了。

  数字化处理(string)

  经常会遇到这样一种情况,有一个数字,需要把每一位给提取出来,如果用取余数的方法,花费的时间就会很长,所以可以当成字符串来处理,方便、省时。

  例子:求一个整数各位数的和

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s;
    s = "123456789";
    int sum = 0;
    for(int i = 0; i < s.size(); ++i)
    {
        switch(s[i])
        {
            case '1': sum += 1;break;
            case '2': sum += 2;break;
            case '3': sum += 3;break;
            case '4': sum += 4;break;
            case '5': sum += 5;break;
            case '6': sum += 6;break;
            case '7': sum += 7;break;
            case '8': sum += 8;break;
            case '9': sum += 9;break;
        }
    }
    
    cout << sum << endl;
    
    return 0;
}
 string与char *

#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

int main()
{
    string s_string;
    char s_char[1000];
    scanf("%s",s_char);

    s_string = s_char;

    //printf输出char* 时用c_str处理
    printf(s_string.c_str());
    cout << endl;

    printf("%s",s_char);
    cout << endl;

    cout << s_char << endl;
    cout << s_string << endl;
    return 0;
}

sscanf
#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

int main()
{
    string s1,s2,s3;
    char sa[100],sb[100],sc[100];
    sscanf("abc 123 wcd","%s%s%s",sa,sb,sc);
    s1 = sa;
    s2 = sb;
    s3 = sc;
    cout << s1 << " " << s2 << " " << s3 << endl;

    //将字符串分离成数字,分隔符为',''$'
    int a,b,c;
    sscanf("4,5$6","%d,%d$%d",&a,&b,&c);
    cout << a << " " << b << " " << c << endl;
    return 0;
}


 string与数值相互转换( sprintf <sstream> )

#include<iostream>
#include<string>
#include<sstream>
#include<cstdio>

using namespace std;

//c++ 方法 把数转换为string
string converToString(double x)
{
    ostringstream o;
    if( o << x)
    {
        // str()没有'\0' c_str有
        return o.str();
    }
    return "error";
}

double converFromString(const string &s)
{
    istringstream i(s);
    double x;
    if( i >> x)
    {
        return x;
    }
    //if error
    return 0.0;
}
int main()
{
    char b[100];
    string s1;

    //c语言方法
    sprintf(b,"%d",1987);
    s1 = b;
    cout << s1 << endl;

    string s2 = converToString(1954);
    cout << s2 << endl;

    string s3 = "202";
    int c = converFromString(s3);
    cout << c << endl;

    string s4 = "casacsa6";
    int d = converFromString(s4);
    cout << d << endl;

    string s5 = "21abf4";
    int f = converFromString(s5);
    cout << f << endl;

    return 0;
}

set容器

  set是用红黑树的平衡二叉索引树的数据结构来实现的,插入时,它会自动调节二叉树排列,把元素放到适合的位置,确保每个子树根节点的键值大于左子树所有的值、小于右子树所有的值,插入重复数据时会忽略。set迭代器采用中序遍历,检索效率高于vector、deque、list,并且会将元素按照升序的序列遍历。set容器中的数值,一经更改,set会根据新值旋转二叉树,以保证平衡,构建set就是为了快速检索(python中的set一旦建立就是一个常量,不能改的)。



 multiset,与set不同之处就是它允许有重复的键值。

  正反遍历,迭代器iterator、reverse_iterator

#include<iostream>
#include<set>

using namespace std;

struct Comp
{
    //重载()
    bool operator()(const int &a, const int &b)
    {
        return a > b;
    }
};
int main()
{
    set<int,Comp> v;
    v.insert(1);
    v.insert(3);
    v.insert(5);
    v.insert(2);
    v.insert(4);
    v.insert(3);
  
    for(set<int,Comp>::iterator it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << endl;

    for(set<int,Comp>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit)
    {
        cout << *rit << " ";
    }
    cout << endl;

    return 0;
}


2、元素本身就是结构体,直接把比较函数写在结构体内部,下面的例子依然降序:

#include<iostream>
#include<set>
#include<string>

using namespace std;

struct Info
{
    string name;
    double score;

    //重载 <
    bool operator < (const Info &a) const
    {
        return a.score < score;
    }
};
int main()
{
    set<Info> s;
    Info info;

    info.name = "abc";
    info.score = 123.3;
    s.insert(info);

    info.name = "EDF";
    info.score = -23.53;
    s.insert(info);


    info.name = "xyz";
    info.score = 73.3;
    s.insert(info);
    
    for(set<Info>::iterator it = s.begin(); it != s.end(); ++it)
    {
        cout << (*it).name << ":" << (*it).score << endl;
    }
    cout << endl;

    for(set<Info>::reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit)
    {
        cout << (*rit).name << ":" << (*rit).score << endl;
    }
    cout << endl;

    return 0;
}


 multiset与set的不同之处就是key可以重复,以及erase(key)的时候会删除multiset里面所有的key并且返回删除的个数。



  map

  map也是使用红黑树,他是一个键值对(key:value映射),便利时依然默认按照key程序的方式遍历,同set。



#include<iostream>
#include<map>
#include<string>

using namespace std;

int main()
{
    map<string,double> m;

    //声明即插入
    m["li"] = 123.4;
    m["wang"] = 23.1;
    m["zhang"] = -21.9;
    m["abc"] = 12.1;
    for(map<string,double>::iterator it = m.begin(); it != m.end(); ++it)
    {
        //first --> key second --> value
        cout << (*it).first << ":" << (*it).second << endl;
    }
    cout << endl;
    return 0;
}



 用map实现数字分离

  string --> number

  之前用string进行过数字分离,现在使用map

#include<iostream>
#include<map>
#include<string>

using namespace std;

int main()
{
    map<char,int> m;

    m['0'] = 0;
    m['1'] = 1;
    m['2'] = 2;
    m['3'] = 3;
    m['4'] = 4;
    m['5'] = 5;
    m['6'] = 6;
    m['7'] = 7;
    m['8'] = 8;
    m['9'] = 9;
    /*
        等价于
        for(int i = 0; i < 10; ++i)
        {
            m['0' + i] = i;
        }
    */

    string sa;
    sa = "9876543210";
    int sum = 0;
    for( int i = 0; i < sa.length(); ++i)
    {
        sum += m[sa[i]];
    }
    cout << sum << endl;
    return 0;
}

用map实现数字分离

  string --> number

  之前用string进行过数字分离,现在使用map

#include<iostream>
#include<map>
#include<string>

using namespace std;

int main()
{
    map<char,int> m;

    m['0'] = 0;
    m['1'] = 1;
    m['2'] = 2;
    m['3'] = 3;
    m['4'] = 4;
    m['5'] = 5;
    m['6'] = 6;
    m['7'] = 7;
    m['8'] = 8;
    m['9'] = 9;
    /*
        等价于
        for(int i = 0; i < 10; ++i)
        {
            m['0' + i] = i;
        }
    */

    string sa;
    sa = "9876543210";
    int sum = 0;
    for( int i = 0; i < sa.length(); ++i)
    {
        sum += m[sa[i]];
    }
    cout << sum << endl;
    return 0;
}


 deque

  deque和vector一样,采用线性表,与vector唯一不同的是,deque采用的分块的线性存储结构,每块大小一般为512字节,称为一个deque块,所有的deque块使用一个Map块进行管理,每个map数据项记录各个deque块的首地址,这样以来,deque块在头部和尾部都可已插入和删除元素,而不需要移动其它元素。使用push_back()方法在尾部插入元素,使用push_front()方法在首部插入元素,使用insert()方法在中间插入元素。一般来说,当考虑容器元素的内存分配策略和操作的性能时,deque相对vectore更有优势。(下面这个图,我感觉Map块就是一个list< map<deque名字,deque地址> >)



插入删除

  遍历当然可以使用下标遍历,在这里使用迭代器。

#include <iostream>
#include <deque>

using namespace std;

int main()
{
    deque<int> d;

    //尾部插入
    d.push_back(1);
    d.push_back(3);
    d.push_back(2);
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl << endl;

    //头部插入
    d.push_front(10);
    d.push_front(-23);
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl << endl;

    d.insert(d.begin() + 2,9999);
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl << endl;

    //反方向遍历
    for(deque<int>::reverse_iterator rit = d.rbegin(); rit != d.rend(); ++rit )
    {
        cout << (*rit) << " ";
    }
    cout << endl << endl;

    //删除元素pop pop_front从头部删除元素 pop_back从尾部删除元素 erase中间删除 clear全删
    d.clear();
    d.push_back(1);
    d.push_back(2);
    d.push_back(3);
    d.push_back(4);
    d.push_back(5);
    d.push_back(6);
    d.push_back(7);
    d.push_back(8);
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl;

    d.pop_front();
    d.pop_front();
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl;

    d.pop_back();
    d.pop_back();
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl;

    d.erase(d.begin() + 1);
    for(deque<int>::iterator it = d.begin(); it != d.end(); ++it )
    {
        cout << (*it) << " ";
    }
    cout << endl;
    return 0;
}

list

  list<int> l

  插入:push_back尾部,push_front头部,insert方法前往迭代器位置处插入元素,链表自动扩张,迭代器只能使用++--操作,不能用+n -n,因为元素不是物理相连的。

  遍历:iterator和reverse_iterator正反遍历

  删除:pop_front删除链表首元素;pop_back()删除链表尾部元素;erase(迭代器)删除迭代器位置的元素,注意只能使用++--到达想删除的位置;remove(key) 删除链表中所有key的元素,clear()清空链表。

  查找:it = find(l.begin(),l.end(),key)

  排序:l.sort()

  删除连续重复元素:l.unique() 【2 8 1 1 1 5 1】 --> 【 2 8 1 5 1】

  bitset

  从来没用过,上两幅图吧就:



stack(后进先出)

  这个印象深刻,学数据结构的时候做表达式求值的就是用的栈。


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

int main()
{

    stack<int> s;
    s.push(1);
    s.push(2);
    s.push(4);
    s.push(5);

    cout << s.size() << endl;

    while(s.empty() != true)
    {
        cout << s.top() << endl;
        s.pop();
    }
    return 0;
}


  stack然我唯一费解之处在于,貌似它没有iterator,可以试试s.begin()编译器报错的。

  queue(先进先出)



queue有入队push(插入)、出队pop(删除)、读取队首元素front、读取队尾元素back、empty,size这几种方法

  priority_queue(最大元素先出)



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

int main()
{

    priority_queue<int> pq;

    pq.push(1);
    pq.push(3);
    pq.push(2);
    pq.push(8);
    pq.push(9);
    pq.push(0);

    cout << "size: " << pq.size() << endl;

    while(pq.empty() != true)
    {
        cout << pq.top() << endl;
        pq.pop();
    }
    return 0;
}


重载操作符同set重载操作符。

我不是代码的原创者,我只是代码的搬运工。

原文地址:http://www.cnblogs.com/duoduo369/archive/2012/04/12/2439118.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值