C++ 如何遍历容器- -数组、string、vector
目录
数组
首先定义一个数组
int arr[5] = { 1,0,0,8,6 };
传统for循环
for (int i = 0; i < 5; i++) {
cout << "arr[" << i << "]=" << arr[i] << endl;
}
while循环
int i = 0;
while (i < 5) {
cout << "arr[" << i << "]=" << arr[i] << endl;
i++;
}
范围for循环
for (auto c : arr)
{
cout << "arr[" << "x" << "]=" << c << endl;
}
指针遍历
for (int *ptr = arrh; ptr < &arrh[5]; ptr++) {
cout << "arr[" << ptr << "]=" << *ptr << endl;
}
数组类型无法使用迭代器进行遍历
string
首先定义一个string字符串类型
string str("Hello");
推荐使用范围for循环和迭代器遍历
传统for循环
for (int i = 0; i < str.size(); i++) {
cout << "str[" << i << "]:" << str[i] << endl;;
}
范围for循环
string str("Hello");
for (auto c : str) {
cout << c << " ";
}
迭代器
string::const_iterator it_begin = str.cbegin();
while (it_begin != str.cend()) {
cout << *it_begin << " ";
it_begin++;
}
指针遍历
char* c = &str[0];
while (*c) {
cout << *c << " ";
c++;
}