您的位置:首页 > 编程语言 > C语言/C++

c++ primer 第9章 顺序容器

2010-06-17 15:12 309 查看
容器的构造 需要类的构造函数

io不支持复制构造函数和赋值构造函数,所以不能作为容器的对象。

vector 和 deque 支持元素的随机访问。

list容器迭代器不支持算术运算,也不支持关系运算。

倒序输出容器元素
    int a[]={1,2,3,4,5,6,7,8,9};
    list<int>temp(a,a+9);
    list<int>::iterator iter1=temp.begin();
    list<int>::iterator iter2=temp.end();
    while (iter2!=iter1)
        cout<<*(--iter2)<<endl;

 

#include  "item_base.h"
#include  "test.h"
#include <string.h>

int main(void)
{
    int a[]={1,2,3,4,5,6,7,8,9};
    list<int>temp(a,a+9);
    list<int>::iterator iter;
    list<int>::iterator iter1=temp.begin();
    list<int>::iterator iter2=temp.end();
   /*
    while (iter2!=iter1)
        cout<<*(--iter2)<<endl;
   for(iter=temp.end();iter!=temp.begin();)
   {
        cout<<*(--iter)<<endl;
   }

   //这个是错误的
   for(iter=temp.end();iter!=temp.begin();--iter)
   {
        cout<<*iter<<endl;
   }
   */
    return 0;
}

 

while(first!=last)
{
 ...
 ++first;
}

 

string str;
list<string>temp;

list<string>::iterator iter=temp.begin();

while(cin>>str)
 iter=temp.insert(iter,str);

这段相当于push_front       注意   iter=temp.insert()   这有个重置工作,insert函数返

回指向新插入元素的迭代器。容器添加元素可能会使迭代器失效。

 

 

 

bool findint(vector<int>::iterator beg,vector<int>::iterator end, int val)
{
    while(beg!=end)
    {
        if(*beg==val)
        {
            break;
        }
        else
            beg++;
    }
    if(beg!=end)
        return true;
    else
        return  false;
}
/*
vector<int>::iterator findint(vector<int>::iterator beg,vector<int>::iterator end,int val)
{
    while(beg!=end)
    {
        if(*beg==val)
        {
            break;
        }
        else
            ++beg;
    }
    return beg;
}

*/

    /*
    //为什么出错,再看看
    vector<string>temp(10);
    vector<string>::iterator iter=&temp[0];
    */

    /*
    vector<string>temp;
    string str;
    cout<<"please input the string /n";
    while(cin>>str)
    {
        temp.push_back(str);
    }
    copy(temp.begin(),temp.end(),ostream_iterator<string>(cout,"/n"));
    */

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息