首页 > 代码库 > c++第十八章-(容器和算法)
c++第十八章-(容器和算法)
容器和算法
容器:
- 容器的概念:能容纳两个或更多个值的数据结构,通常我们称为容器(container)。
- 这么说,数组是唯一直接支持的容器,但数组并不适合用来解决所有的问题。
- 上一节利用模板就实现了一种新的容器(栈Stack)。
- 老一辈程序员为我们提供了一种容器库,Standard Template Library。STL库。
算法:
- 数组大小固定的,后来引入了一种新的数据类型,vector向量,
- 声明: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;}
.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。