首页 > 代码库 > c++第十八章-(容器和算法)

c++第十八章-(容器和算法)

容器和算法

容器:

  1. 容器的概念:能容纳两个或更多个值的数据结构,通常我们称为容器(container)。
  2. 这么说,数组是唯一直接支持的容器,但数组并不适合用来解决所有的问题。
  3. 上一节利用模板就实现了一种新的容器(栈Stack)。
  4. 老一辈程序员为我们提供了一种容器库,Standard Template Library。STL库。

算法:

  1. 数组大小固定的,后来引入了一种新的数据类型,vector向量,
  2. 声明:std::vector<type> vectorName;
#include <vector>int main(int argc, const char * argv[]){    std::vector<std::string> names;        names.push_back("jobs");    names.push_back("小甲鱼");    names.push_back("bill");        for (int i = 0; i < names.size(); i++)    {        std::cout << names[i] << "\n";    }        return 0;}

3.迭代器(iterator):智能指针,具有遍历复杂数据结构的能力。

因为各种迭代器的接口相同,型号却不同,这就是所谓泛型程序设计的概念:所有的操作都使用相同的接口,虽然他们的具体实现不一样。

4.迭代器的真正价值体验在它们可以和所有的容器配合使用,而使用迭代器去访问容器元素的算法可以和任何一种容器配合使用。

#include <vector>int main(int argc, const char * argv[]){    std::vector<std::string> names;        names.push_back("jobs");    names.push_back("小甲鱼");    names.push_back("bill");        /**        for (int i = 0; i < names.size(); i++)    {        std::cout << names[i] << "\n";    }     *     */        std::vector<std::string>::iterator iter = names.begin();    while (iter != names.end())    {        std::cout << *iter << std::endl;        ++iter;    }    return 0;}

5.c++标准库提供一个专门处理算法问题的算法库algorithm,只要在源文件里:#include<algorithm>就可以用,如:std::sort(beginIterator,endIterator);

#include <vector>#include <algorithm>int main(int argc, const char * argv[]){    std::vector<std::string> names;        names.push_back("jobs");    names.push_back("Rola");    names.push_back("bill");    names.push_back("Larry");    names.push_back("Lucy");    names.push_back("apple");        std::sort(names.begin(), names.end());        /**        for (int i = 0; i < names.size(); i++)    {        std::cout << names[i] << "\n";    }     *     */        std::vector<std::string>::iterator iter = names.begin();    while (iter != names.end())    {        std::cout << *iter << std::endl;        ++iter;    }    return 0;}

.