📜  如何在 C++ 中迭代集合映射(1)

📅  最后修改于: 2023-12-03 14:52:15.575000             🧑  作者: Mango

在 C++ 中迭代集合映射

简介

在 C++ 中,集合和映射是两种常见的数据结构。集合是一组无序的唯一元素的集合,而映射是一组键值对的集合,其中每个键都唯一对应一个值。在这个介绍中,我们将探讨如何在 C++ 中有效地迭代集合和映射。

迭代集合

C++ 中迭代集合有多种方式,包括使用循环和 iterator 迭代器。

使用循环迭代集合

一种常见的迭代集合的方式是使用循环。下面是使用 for 循环迭代集合的示例代码:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> collection = {1, 2, 3, 4, 5};

    for (int i = 0; i < collection.size(); i++) {
        std::cout << collection[i] << " ";
    }

    return 0;
}

在上面的示例中,我们创建了一个 std::vector<int> 类型的集合,并使用 for 循环迭代打印集合中的每个元素。

使用 iterator 迭代器迭代集合

另一种迭代集合的方式是使用迭代器。迭代器提供了灵活的方式来遍历集合中的元素。下面是使用迭代器迭代集合的示例代码:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> collection = {1, 2, 3, 4, 5};

    for (std::vector<int>::iterator it = collection.begin(); it != collection.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}

在上面的示例中,我们使用 collection.begin() 获取集合的起始迭代器,collection.end() 获取集合的结束迭代器,并使用迭代器 it 遍历集合中的每个元素。

迭代映射

与迭代集合类似,C++ 中迭代映射也可以使用循环和 iterator 迭代器来实现。

使用循环迭代映射

下面是使用 for 循环迭代映射的示例代码:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> map = {{"A", 1}, {"B", 2}, {"C", 3}};

    for (const auto& pair : map) {
        std::cout << pair.first << " -> " << pair.second << std::endl;
    }

    return 0;
}

在上面的示例中,我们创建了一个 std::map<std::string, int> 类型的映射,并使用 for 循环迭代打印映射中的每个键值对。

使用 iterator 迭代器迭代映射

下面是使用迭代器迭代映射的示例代码:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> map = {{"A", 1}, {"B", 2}, {"C", 3}};

    for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it) {
        std::cout << it->first << " -> " << it->second << std::endl;
    }

    return 0;
}

在上面的示例中,我们使用 map.begin() 获取映射的起始迭代器,map.end() 获取映射的结束迭代器,并使用迭代器 it 遍历映射中的每个键值对。

结论

在 C++ 中,我们可以使用循环和 iterator 迭代器来有效地迭代集合和映射。无论是通过循环还是迭代器,都可以轻松地访问集合和映射中的元素。迭代集合和映射是编程中一项基础技能,可以帮助程序员更好地操作和处理数据。