zoukankan      html  css  js  c++  java
  • 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] << "
    ";
        }
        
        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] << "
    ";
        }
         *
         */
        
        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] << "
    ";
        }
         *
         */
        
        std::vector<std::string>::iterator iter = names.begin();
        while (iter != names.end())
        {
            std::cout << *iter << std::endl;
            ++iter;
        }
        return 0;
    }

    .

  • 相关阅读:
    .net core系列之《.net平台历程介绍以及.net framework和.net core对比》
    C++ 拷贝构造函数
    C++ const引用
    C++ 引用和指针
    C++ 将派生类赋值给基类(向上转型)
    C++ 虚继承
    C++ 基类和派生类的构造函数以及析构函数
    C++ 类继承时的作用域嵌套和对象内存模型
    C++ private + protected + public
    C++ const成员变量、成员函数和对象
  • 原文地址:https://www.cnblogs.com/huen/p/3849349.html
Copyright © 2011-2022 走看看