第十章泛型算法

只读

find(v.begin(), v.end(), 1);

count(v.begin(), v.end(), 1);

int sum = accumulate(v.begin(), v.end(), 0);  //第三个值决定返回值的类型

string s1 = accumulate(v.begin(), v.end(), string(""));

string s = "abcdefg";
string s2 = accumulate(s[1], s[3],"");  //wrong,传递一个字符串字面值,用于保存的""对象类型是const char*, 应为 string("")
equal(v1.begin(), v1.end(), v2.begin());

 

 

fill(v.begin(), v.begin(0 + v.size(0) / 2, 10)

fill_n(v.begin(), 10, 0)

 

vector<int> v;

auto iter = back_inserter(v);  //back_inserter接受一个指向容器的引用,返回一个与该容器绑定的插入迭代器,通过给迭代器赋值时,赋值运算会调用push_back将一个具有定值的元素添加到容器中

*iter = 42;

fill_n(back_inserter(v), 10, 0);

 

 

重排

sort和stable_sort

void elimDups(vector<string> &words)
{
    sort(words.begin(), words.end());
    auto unique_end = unique(words.begin(), words.end());
    words.erase(unique_end, words.end());
}

stable_sort内部实现是归并排序,sort是快速排序。所以一个稳定,一个不稳定。

 

习题10.9

实现你自己的elimDups。分别在读取输入后、调用unique后以及调用erase后打印vector的内容。

void elimDups(vector<string> &words)
{
    sort(words.begin(), words.end());
    auto unique_end = unique(words.begin(), words.end());
    words.erase(unique_end, words.end());
}

 10.9

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

#include <iostream>
#include <vector>
#include <fstream>
#include <iterator>

using namespace std;
int main()
{
    ifstream file("C:\\test.txt");
    istream_iterator<string> int_in(file), int_eof;
    vector<string> v;
    while(int_in != int_eof)
        v.push_back(*int_in++);
}

 

posted @ 2021-05-26 11:38  11YS  阅读(34)  评论(0编辑  收藏  举报