C++ list数组遍历
时间: 2023-08-20 20:06:07 浏览: 67
要遍历 C++ 中的 list(链表),可以使用迭代器(iterator)。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <list>
using namespace std;
int main() {
// 创建一个 list 对象
list<int> mylist = {1, 2, 3, 4, 5};
// 遍历 list
list<int>::iterator it;
for (it = mylist.begin(); it != mylist.end(); ++it) {
cout << *it << " ";
}
return 0;
}
```
在这个示例中,我们首先创建了一个包含 5 个元素的 list 对象。然后,我们使用迭代器 it 遍历了整个 list,将每个元素输出到控制台。注意,我们需要使用 `*it` 来访问迭代器指向的元素。
相关问题
python 数组遍历便捷写法
以下是Python中数组遍历的便捷写法:
1. 遍历元组元素
```python
tuple1 = ('h', 'e', 'l', 'l', 'o')
for item in tuple1:
print(item)
```
2. 遍历列表元素
```python
list1 = ['Python', 'Java', 'C++', 'JavaScript']
for item in list1:
print(item)
```
3. 遍历集合元素
```python
set1 = {'a', 'b', 'c'}
for item in set1:
print(item)
```
4. 遍历整数列表
```python
intlist = [1, 2, 3, 4, 5]
for item in intlist:
print(item)
```
c++9 如何遍历map数组
在C++11标准中,可以使用`range-based for loop`语法来遍历`map`数组,这种语法可以让代码更加简洁易读。下面是一个例子:
```c++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
// 创建一个map数组
map<string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
// 遍历map数组
for (auto& [key, value] : myMap)
{
cout << key << " : " << value << endl;
}
return 0;
}
```
在这个例子中,我们使用`range-based for loop`语法遍历了整个`myMap`数组,并输出了其中的键和值。需要注意的是,这里使用了`auto&`来引用迭代器,而`[key, value]`则表示每次循环都会自动解包出当前键值对的键和值。这样,我们就可以直接使用`key`和`value`来访问当前键值对的键和值了。
`range-based for loop`语法不仅可以用于遍历`map`数组,还可以用于遍历其他容器类型,例如`vector`、`list`、`set`等等。