C++ STL容器的使用技巧
在本文中,我们将介绍C++ STL(Standard Template Library)容器的使用技巧。STL是C++标准库的一部分,提供了一套丰富的容器类模版,用于快速、高效地存储和操作数据。
阅读更多:C++ 教程
vector容器
vector是一种动态数组,可以在运行时根据需要自动调整大小。常见的操作有插入元素、删除元素、查找元素等。
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums; // 定义一个vector容器,存储int类型的元素
// 向vector中插入元素
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
// 使用迭代器遍历vector中的元素
for(auto it = nums.begin(); it != nums.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 删除vector中的元素
nums.pop_back();
// 使用下标访问vector中的元素
std::cout << nums[0] << std::endl;
return 0;
}
在上面的示例中,我们首先创建一个vector容器nums,并使用push_back函数将元素1、2、3依次插入容器中。然后使用迭代器遍历容器中的元素,并使用pop_back函数删除了最后一个元素。最后使用下标访问容器中的元素,输出了第一个元素的值。
list容器
list是一种双向链表,可以在任意位置高效地插入和删除元素。常见的操作有插入元素、删除元素、反转链表等。
#include <list>
#include <iostream>
int main() {
std::list<int> nums; // 定义一个list容器,存储int类型的元素
// 向list中插入元素
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
// 使用迭代器遍历list中的元素
for(auto it = nums.begin(); it != nums.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 删除list中的元素
nums.pop_back();
// 使用reverse函数反转list
nums.reverse();
// 使用for-each遍历list中的元素
for(const auto& num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
在上面的示例中,我们首先创建一个list容器nums,并使用push_back函数将元素1、2、3依次插入容器中。然后使用迭代器遍历容器中的元素,并使用pop_back函数删除了最后一个元素。接着使用reverse函数反转了容器中的元素顺序,并使用for-each遍历输出了反转后的元素。
map容器
map是一种关联容器,可以按照键值对的方式存储和访问数据。常见的操作有插入元素、删除元素、查找元素等。
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> students; // 定义一个map容器,存储学生姓名和分数
// 向map中插入元素
students.insert(std::make_pair("Alice", 95));
students.insert(std::make_pair("Bob", 80));
students.insert(std::make_pair("Charlie", 90));
// 使用迭代器遍历map中的元素
for(auto it = students.begin(); it != students.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 查找map中的元素
auto it = students.find("Bob");
if (it != students.end()) {
std::cout << "Bob's score is " << it->second << std::endl;
}
// 删除map中的元素
students.erase("Charlie");
return 0;
}
在上面的示例中,我们首先创建一个map容器students,并使用insert函数插入了三个键值对。然后使用迭代器遍历map中的元素,并使用find函数查找了Bob的分数并输出。最后使用erase函数删除了Charlie的信息。
总结
本文介绍了C++ STL容器的使用技巧,包括vector、list和map容器的常见操作和示例。熟练掌握STL容器的使用技巧,可以提高代码编写效率和程序性能。在实际开发中,根据具体的需求和数据结构选择合适的容器,合理运用容器的功能和特性,可以简化代码逻辑,提高程序可读性和可维护性。希望本文对读者有所帮助,谢谢阅读!
极客笔记