c++primer 第十章习题

来源:互联网 发布:数据透视图 编辑:程序博客网 时间:2024/04/29 05:02

10.3用accumulate求一个vector<int>的和

std::vector<int>a{1,2,3};

int i =std::accumulate(a.begin(),a.end(),0);

10.4假定v是一个vector<double>,那么调用accunulate(v.cbegin(),v.cend(),0)有什么错误

从“double”转换到“int”,可能丢失数据

10.5在本节对名册调用equal的例子中,如果两个名册保存的是c风格字符串而不是string,会发生什么

'std::equal::_Unchecked_iterators::_Deprecate':Call to 'std::equal' with parameters that may be unsafe - this call relies onthe caller to check that the passed values are correct. To disable thiswarning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use VisualC++ 'Checked Iterators'         Debug      d:\vs2015\vc\include\xutility  2983        

 

 

10.6编写函数,使用filln讲一个序列中的int设置为0

void Replace(vector<int> &m,intn)

{

         std::fill_n(m.begin(),m.end(),n);

 

 

10.8本节提到过,标准库算法不会改变他们所操作的容器的大小,为什么使用backinseter不会使这一断言失效

标准库算法不直接操控容器,操控迭代器来间接操控容器、

 

10.9实现你自己的Elimdups,测试你的程序,分别在读取输入后调用unique时调用erase打印vector的值

void Print(constvector<int> &a)

{

                                     for (auto m= a.begin(); m != a.end(); m++)

                                     cout<< *m << " ";

                                     cout<< endl;

}

//消除不重复元素的

voidNoEli(vector<int> &a)

{

                                     Print(a);

                                     sort(a.begin(),a.end());

                                     Print(a);

                                     auto end =unique(a.begin(),a.end());

                                     Print(a);

 

                                     a.erase(end,a.end());

                                     Print(a);

 

}

 

10.10你认为算法不改变容器大小的原因?

算法都是操作迭代器,来间接操作容器

 

10.11编写程序,使用stablesort和isshort将传递给你的elimdups版本的vector排序。打印vector的内容

vector<int>a{0,5,6,5,8,6,5,7,2,5,4,63,2};

NoEli(a);

stable_sort(a.begin(),a.end(),isok);

 

10.12编写名为CompareIsgn的函数,比较两个对象的isbn成员,使用这个函数排序一个保存Sales的vector

vector<Sales_item>book;

std::stable_sort(book.begin(),book.end(),CompareIsbn);

 

10.13标准库定义了名为partiton的算法,他接受一个predicate,对容器内容进行划分,使predicate为true的排在前半部分,而使另一部分排在后面,算法返回一个迭代器指向最后一个使predicate为true的元素后面一个位置。。。编写函数,接受一个string返回一个bool值指出string是否有5个或更多字符。使用此函数划分word,打印长度大于5的元素

boolisbigstring(const string &a)

{

                                     returna.size() > 4;

}

voidSplitWord(vector<string> &t)

{

                                     auto m =unique(t.begin(), t.end());

                                     t.erase(m,t.end());

                                     auto k =partition(t.begin(), t.end(), isbigstring);

                                     t.erase(k,t.end());

}

 

10.14编写一个lambda,接受两个int,返回他们的和

                                     auto adds =[](int a, int b)->int {return a + b; };

                                     int m, n;

                                     cout<<adds(m,n) << endl;

10.15编写一个lambda,捕获他所在函数的int,并接受一个int,返回他们的和

void a(int u)

{

                                     auto adds =[u](int a)->int {return a + u; };

                                     cout<<adds(5) << endl;

}

 

10.16使用lambda,编写你自己版本的biggies

voidBiggies(std::vector<std::string> &words, std::vector<std::string>::size_typei)

{

    NoEli(words);

   stable_sort(words.begin(), words.end(), [](const std::string &a,const std::string &b)->bool {returna.size() < b.size(); });

    auto first = find_if(words.begin(),words.end(), [i](conststring &a)->bool {returna.size() >= i; });

    auto num = words.end() - first;

    std::cout<< "count=" << num << std::endl;

    for_each(first,words.end(), [](const std::string &a) {std::cout<< a << " "; });

    cout<< endl;

}

 

10.17重写10.12的程序,在对sort的调用使用lambda

 

10.18重写biggies用partition代替findif

voidBiggies(std::vector<std::string> &words, std::vector<std::string>::size_typei)

{

    NoEli(words);

   stable_sort(words.begin(), words.end(), [](const std::string &a,const std::string &b)->bool {returna.size() < b.size(); });

    auto first = partition(words.begin(),words.end(), [i](conststring &a)->bool {returna.size() >= i; });

    auto num = words.begin() - first;

    std::cout<< "count=" << num << std::endl;

    for_each(words.begin(),  first, [](const std::string &a) {std::cout<< a << " "; });

    cout<< endl;

}

 

10.20标准库定义了一个名为countif的算法,类似findif,此函数接受一对迭代器,表示输入范围,一个predicate,会对每个元素执行,countif返回计数器,表示为真了多少次。使用countif重写我们程序中统计有多少单词长度超过6的部分

intGetCountWordLength(std::vector<std::string> &a, std::vector<std::string>::size_typei)

{

    return count_if(a.begin(),a.end(), [i](conststring& m)->bool {returnm.size() >= i; });

}

10.21

    auto m = [m]()mutable ->bool {if (m > 0) { m--; }return m == 0; };

 

10.22重写10.19的程序,用函数代替lambda

boolisstort(conststring& a,std::string::size_typei)

{   return a.size() >= i;}

intmain()

{

    vector<std::string> a{"afds","addsf","adsfawef","adf","adfdasfef"};

find_if(a.begin(),a.end(),bind(isstort,std::placeholders::_1,6));

return 0;}

10.23

Bind接受一个函数,n个该函数参数

10.24

intfindMax(vector<int> &a,const std::string &m)

{

    auto n= find_if(a.begin(),a.end(),bind(isintstort,std::placeholders::_1,m));

    return *n;

}

 

10.26解释三种插入迭代器的不同之处

Backinserter    使用时,总是插入到最后的位置

Frontinserter    使用时,总是插入到容器第一个的位置

Inserter        调用后得到一个迭代器,使用时,会把元素插入到迭代器原先指向元素之

10.27uniquecopy,接受第三个迭代器,表示拷贝不重复元素的摩的位置。使用uniquecopy讲一个vector中的元素拷贝到一个初始为空的list

    vector<int>d{ 1,5,2,3,7,5,1};

    list<int> dd;

    auto c =back_inserter(dd);

    unique_copy(d.begin(),d.end(),c);

10.28一个vector保存1~9,将其拷贝到三个容器中,对每种输出来说,输出序列是什么。

 

10.29编写程序,使用流迭代器读取一个文本文件,存入一个vector的string里。

std::vector<std::string>& Read(char*File)

{

    std::ifstream i(File, std::ios::in);

    std::istream_iterator<std::string> is(i), eof;

    std::vector<std::string> str;

    while (is != eof)

    {

        str.push_back(*is++);

    }

     return str;

}

10.30使用流迭代器,sort和copy从标准输入读取一个整数序列,将其排序,并将结果写到标准输出

void PrintSort()

{

    std::istream_iterator<int>is(std::cin), eof;

    std::ostream_iterator<int>os(std::cout," ");

        std::vector<int >a;

    while (is != eof)

    {

        a.push_back(*is++);

    }

    std::sort(a.begin(), a.end());

    std::copy(a.begin(), a.end(), os);

}

10.31修改前一题的程序,使其只打印不重复的元素,你的程序应使用uniquecopy

void PrintSort()

{

    std::istream_iterator<int>is(std::cin), eof;

    std::ostream_iterator<int>os(std::cout," ");

        std::vector<int >a;

    while (is != eof)

    {

        a.push_back(*is++);

    }

    std::sort(a.begin(), a.end());

    std::unique_copy(a.begin(), a.end(), os);

}

10.33编写程序,接受三个参数,一个输入文件,两个输出文件的文件名。输入文件保存的是整数,使用istreamiterator读取输入文件,使用ostreamiterator将奇数存入第一的输出文件,将偶数存入第二个输出文件,每个值都独占一行

void out(char*in, char *o1,char *o2)

{

    std::ifstream i(in, std::ios::in);

    std::ofstream f1(o1, std::ios::out);

    std::ofstream f2(o2, std::ios::out);

    std::vector<int> m;

    std::istream_iterator<int> is(i),eof;

    std::ostream_iterator<int> os1(f1,"\n"), os2(f2, "\n");

 

    while (is != eof)

    {

        m.push_back(*is++);

    }

 

    copy_if(m.begin(), m.end(), os1, [](constint& a)->bool {returna % 2 == 1; });

    copy_if(m.begin(), m.end(), os2, [](constint& a)->bool {returna % 2 == 0; });

}

10.34使用reverseiterator逆序打印一个vector

void print()

{

    std::vector<int>s{4,5,6,7,8,9 };

    for (auto a = s.rbegin(); a!= s.rend(); a++)

    {

        std::cout << *a<< std::endl;

    }

}

 

10.35使用普通迭代器逆序打印一个vector

void print()

{

    std::vector<int>s{4,5,6,7,8,9 };

    auto a = s.begin();

    auto b = s.end();

    b--;

    while (a!=b)

    {

        std::cout << *b << std::endl;

        b--;

    }

    std::cout << *a << endl;

}

 

10.36使用find在一个int的list中查找最后一个值为0的元素

    std::list<int> a;

     auto  m=find_if(a.rbegin(), a.rend(), [](constint& a)->bool {returna == 0; });

10.37给定一个包含10个元素的vector,将位置3~7之间的元素逆序拷贝到一个list中

    std::vector<int>x{1,2,3,4,5,6,7,8,9,10 };

    std::list<int> a;

     copy(x.rbegin()+2, x.rend()-2, back_inserter(a));

10.38列出五个迭代器的类别,以及每类迭代器所支持的操作。

输入迭代器

只读、单边扫描、++

比较两个迭代器相等、不等的运算符

递增运算符

读取元素的解引用运算符   ->

输出迭代器

只写、单边扫描、++

递增运算符

读取元素的解引用运算符   ->

前向迭代器

多遍扫描++

可读写

支持所有输入输出的操作

多次读写=保存状态

双向迭代器

多遍扫描++--

可读写

支持所有输入输出的操作

多次读写=保存状态

--

随机访问迭代器

支持全部迭代器运算

提供在常量时间内访问序列中任意元素的能力

10.39list上的迭代器属于哪类 vector?

List          双向迭代器

Vector        随机访问迭代器

 

10.40你认为copy要求那种迭代器 reverse,unique

Copy     单向迭代器

Reverse  双向迭代器

Unique   单向迭代器