STL的应用(2)
vector
容器类
能够存储一系列数据的类
- 序列式容器, 连续存储, 使用下标来进行索引.
- 关联式容器, 使用key-value来进行访问
它是一个序列式容器, 它是有顺序的
它是一个可变长的数组.
例子
// vector例子
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
int main()
{
vector<int> demo;
vector<std::string> demo1;
vector<int*> demo2;
// vector<int&> demo; // 报错 不支持
// vector<const > demo; // 不能放const的东西 ???
vector<std::string> strings(10, "Hello Hades!");
// 在尾部增加
strings.push_back("Hello Hades Studio!");
strings.push_back("Hello Hades Studio!");
// 弹出(删除掉)尾部的数据
cout << strings.pop_back() << std::endl;
// 获取最后一个, 不删除数据
cout << strings.back() << std::endl;
// 获取第一个
cout << strings.front() << std::endl;
for (std::size_t i = 0; i < strings.size(); ++i)
{
cout << strings.at(i) << std::endl;
}
// 赋值 整个容器都清空后变成新的
strings.assign(10, "Hello Hades Studio!!!!!");
for (std::size_t i = 0; i < strings.size(); ++i)
{
cout << strings.at(i) << std::endl;
}
vector<std::string> otherStrings(2, "Hello!");
vector<int> ints(2, 100);
// 赋值 整个容器都清空后变成新的
// 调用的是 vector 的 operator=
strings = otherStrings;
for (std::size_t i = 0; i < strings.size(); ++i)
{
cout << strings.at(i) << std::endl;
}
// 元素的交换
// 调用的是 string 的 operator=
strings[0] = otherStrings[0];
strings.at(0) = "100";
// 执行过程
// string&(vector.at(0)).operator=(char*)
strings.back() = "6666";
}迭代器
代表的是容器中的位置, 而并非对象本身.
可以理解为一个指针.
正向迭代器
双向迭代器
随机访问迭代器
// vector例子
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
int main()
{
vector<std::string> strings(10, "666666");
vector<std::string>::iterator it = strings.begin();
cout << *it << std::endl;
cout << it->c_str() << std::endl;
// for (vector<std::string>::iterator it = strings.begin(); it != strings.end(); ++it)
for (auto it = strings.begin(); it != strings.end(); ++it)
{
cout << *it << std::endl;
}
auto it = strings.end();
// 报错
// begin 和 end 是一个 半开区间
// [ )
// end() 指向的是最后一个元素的下一个
// *it = "8866666";
*(it - 1) = "886666"; ?????????????????????????
for (auto it = strings.begin(); it != strings.end(); ++it)
{
cout << *it << std::endl;
}
vector<std::string> str;
str.push_back("1");
str.push_back("3");
str.push_back("4");
str.push_back("5");
str.push_back("6");
str.push_back("7");
str.push_back("8");
str.push_back("9");
// 在 +1 之前 插入某个数据
str.insert(str.begin() + 1, "2");
// 在 +1 之前 插入10个 10
str.insert(str.begin() + 1, 10, "10");
// 颠倒输出
// for (auto it = str.rbegin(); it != str.rend(); ++it)
for (vector<std::string>::reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
{
cout << *it << std::endl;
}
// 擦除第一个
str.erase(str.begin());
// 范围擦除
str.erase(str.begin(), str.begin() + 10);
// 删除全部
str.clear();
for (auto it = str.begin(); it != str.end(); ++it)
{
cout << *it << std::endl;
}
}如有错误,请提出指正!谢谢.
本文由 花心胡萝卜 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2017-02-19 at 03:59 pm