C++ 如何遍历容器- -数组、string、vector

目录

数组

传统for循环 

while循环 

范围for循环

指针遍历

string

传统for循环

范围for循环

迭代器

指针遍历

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++;
	}

vector~~

posted @ 2021-08-19 17:01  Keep_Silent  阅读(87)  评论(0编辑  收藏  举报