我们知道可以通过下标运算符‘[]’来访问vector对象的元素。
vector是一种标准库容器,除了vector容器标准库还有其他的容器。
所有容器都支持迭代器,但只有少数支持下标运算符。所以使用迭代器更加方便,不会出现问题。
下面是一些实例,运行环境是vs2015,在sublime3中不支持。
#include <string.h>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
#if 0 //vector 1 对向量的基本操作
vector<int>obj;//创建一个向量存储容器 int
for (int i = 0; i<10; i++) // push_back(elem)在容器最后添加数据
{
obj.push_back(i);
cout << obj[i] << ",";
}
for (int i = 0; i<5; i++)//去掉容器最后一个数据
{
obj.pop_back();
}
cout << "\n" << endl;
for (int i = 0; i<obj.size(); i++)//size()容器中实际数据个数
{
cout << obj[i] << ",";//只有向量不为空时,才能通过下标运算符访问向量
}
#endif
//新建向量vector
//std::vector<int> v1;
//std::vector<int> v1(10);
//std::vector<int> v1(10,42);
//std::vector<int> v1{10};//error
#if 0 vector2
std::vector<int> v1{ 10,42 };
if (!v1.empty())
{
int i = v1.size();//获取向量大小
cout << "v1.size() = " << i << endl;
for (int j = 0; j < i; j++)
{
cout << v1[j] << " "; //注意,向量如果没有初始化,则不能使用下标访问向量成员
}
cout << endl;
}
else
{
cout << "v1 is empty\n";
}
#endif
#if 0 //iterator1 通过iterator访问向量成员
std::vector<int> v1{ 10,42 };
//新建迭代器it,it的类型由对象v1的类型决定,若v1是常量则,it类型为const_iterator
//否则it类型为iterator
auto it = v1.cbegin();//cbegin返回值类型为const_iterator,返回值的类型与v1对象类型无关
int count = 0;
while(it != v1.cend())
{
cout << (*it ++) << endl;//通过迭代器打印v1的成员
count ++;
}
cout << "v1 size = " << count << endl;
#endif
//iterator 2 //通过irerator访问string对象,将string中的第一个单词串变成大写
string v_str = "hello world!";
string::iterator it = v_str.begin();//begin返回值类型为iterator,返回值的类型与v1对象类型有关
//将hello变为大写字母形式
while(it != v_str.end() && !isspace(*it))
{
*it = toupper(*it);
it++;
}
cout << v_str.c_str() << endl;//打印字符串的值
system("pause");
return 0;
}
打印结果为HELLO world!