迭代器vector的访问与使用

时间:2022-03-10 04:16:42

一、访问vector的第个元素

#include<iostream>
using namespace std;
int main()
{
string s("some thing");
if(s.begin()!=s.end())
{
auto it=s.begin();
*it=toupper(*it);
//for(decltype(s.size()) i=0;i!=s.size()-1;++i)
int i=3;
cout<<s.begin()[i];
cout<<*it<<endl;
}
说明:auto *it=s.begin();  //*it是解引用
*it=s.begin()[0];
#include<iostream>
#include<vector>
using namespace std;

void main()
{
vector<int> coll;

for (int i = -3; i < 9; ++i){
coll.push_back(i);
}

cout << "number/distance:" << coll.end() - coll.begin() << endl;

vector<int>::iterator pos;//迭代器
for (pos = coll.begin(); pos < coll.end(); ++pos)
cout << *pos << "\t";
cout << endl;

for(decltype(coll.size()) i = 0; i < coll.size(); ++i)
cout << coll.begin()[i] << "\t";//coll.begin[i]d
cout << endl;

//for (pos = coll.begin(); pos < coll.end() - 1; pos += 2)
//cout << *pos << "\t";
//cout << endl;
}