迭代器是一种访问容器的方式,可以访问所有标准库容器(顺序容器和关联容器),下标和at访问方式只适用于string、vector、deque、array,因此类似指针,迭代器是一种间接访问对象的方式。
//1定义一个迭代器,类似vector<int>::size_type,我们不必关注迭代器的类型
std::vector<int>::iterator it;//迭代器能够进行读写
std::vector<int>::const_iterator it;//只能读
//2迭代器访问容器元素
std::vector<int> test_vec(9, 0);
//迭代器访问
for (auto it = test_vec.begin(); it != test_vec.end(); ++it)
{
*it = 1;//test_vec元素为1
}
//下标访问
for (std::vector<int>::size_type i = 0; i < test_vec.size(); ++i)
{
std::cerr << test_vec[i] << std::endl;//打印所有1
}
//at 访问
for (std::vector<int>::size_type i = 0; i < test_vec.size(); ++i)
{
std::cerr << test_vec.at(i) << std::endl;//打印所有1
}