STL用法规则

本文介绍了如何使用STL容器存储对象或对象指针,并详细解释了五条关键规则:选择存储方式、实现复制构造函数、插入对象、遍历容器及删除元素。通过遵循这些规则,开发者可以更有效地利用STL容器。
 

Rule 1:

You can create STL containers that store either objects or pointer to objects.

class TMyClass;
typedef list<TMyClass> TMyClassList; // Stores objects into the list container
typedef list<TMyClass*> TMyClassPtrList; // Stores pointers to object into the list container

Usually, list container that stores the object is used. However, if the object is using a machine resource (handle to file, named pipe, socket or similar), then it is more appropriate to use lists that stores pointers to objects.

If the container stores objects, then it is automatically cleaned up during container destruction. However, if it stores pointers to objects, programmer is responsible to delete all pointers.

Rule 2:

Each class (whose instance will go into the container) must implement at least the copy constructor (it is good to implement also the assignment operator.
class TMyClass {
private:
...
public:
TMyClass(..);

// Copy constructor
TMyClass(const TMyClass& obj) { *this = obj; }

// Assignment operator
TMyClass& operator=(const TMyClass& obj);
...
};

This is necessary since the STL will create a local copy of the object when you insert an object instance into the container. If you do not write a correct code for the copy constructor, object within a list will have some data members uninitialized.

Rule 3:

Inserting an object into the container is done in the following way:

TMyClass object;
TMyClassList myList;
TMyClassList::iterator it;

it = myList.insert(myList.end(), object);
TMyClass *pObject = &(*it);

Previous example shows how to insert an object into the container and obtain a pointer to the object within container. This is necessary since the container will create a new copy of the "object" instance and the original "object" instance is not used any more. In case you are storing pointers to a list, this is not necessary since original pointer is stored into the container.

Rule 4:

Iterating through container is done in the following way:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = &(*it);
// Use pObject
}

However, if you are storing pointers into the container, then the previous code fragment has to be modified to the following:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = *it;
// Use pObject
}

Rule 5:

Removing items from the container is done in the following way:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = &(*it);
if (pObject satisfies some delete criteria) then
myList.erase(it);
// If pointers are stored in a list then add
delete pObject;
}
<think>好的,用户想了解蓝桥杯比赛中STL的使用方法,特别是需要教程和示例代码。首先,我需要回忆蓝桥杯竞赛中常用的STL容器和算法,以及相关的引用资料。根据用户提供的引用,他们提到了map、pair、set、模板等知识点,应该围绕这些内容展开。 首先,确定STL在蓝桥杯中的常见应用场景,比如快速排序、数据管理、键值对处理等。然后,结合引用中的示例代码,比如map的使用、pair的排序规则、set的自定义比较函数,以及类模板的基础语法,这些都是需要涵盖的重点。 接下来,需要组织回答的结构,确保每个部分都有示例代码和实际应用场景。例如,先介绍常用的容器,如vector、map、set,再讲解pair和算法如sort。每个部分要说明其用途,给出代码示例,并引用对应的参考资料。同时,注意用户提到的代码格式要求,比如行内数学公式用$...$,独立公式用$$...$$,但这里可能更多涉及代码块,所以需要正确使用代码标记。 还需要检查示例代码是否符合用户提供的引用内容,比如引用[3]中的字符串拼接代码,引用[4]中的set修改比较方法,引用[2]中的pair比较规则。确保每个示例代码都正确无误,并且标注引用来源。 此外,用户要求生成相关问题,可能需要围绕STL的不同容器、性能优化、应用场景等方面提问,例如如何选择合适容器,或如何自定义排序函数等。 最后,要确保回答符合中文要求,结构清晰,分点说明,并自然融入引用标识。同时,检查是否有遗漏的重要STL组件,如stack、queue、priority_queue等,但根据引用内容,可能集中在map、set、pair、模板等方面,所以可以优先覆盖这些内容。</think>### 蓝桥杯STL使用详解 #### 一、常用STL容器及用法 1. **`pair`容器** 用于存储两个相关联的值,常用于需要返回两个值的场景(如坐标、键值对)。 **示例代码**: ```cpp #include <iostream> #include <utility> using namespace std; int main() { pair<int, string> p = make_pair(2023, "蓝桥杯"); cout << "编号:" << p.first << " 名称:" << p.second << endl; return 0; } ``` **排序规则**:默认按`first`升序,若`first`相同则按`second`升序[^2]。 2. **`map`容器** 基于红黑树实现的有序键值对容器,适合快速查找和去重。 **示例代码**: ```cpp #include <map> #include <string> int main() { map<string, int> score; score["Alice"] = 90; score["Bob"] = 85; // 遍历输出(按键升序) for (auto& entry : score) cout << entry.first << ": " << entry.second << endl; return 0; } ``` **适用场景**:需要按键有序且频繁查询的场景[^1]。 3. **`set`容器** 自动排序且元素唯一的集合,支持快速插入和查找。 **自定义排序**:通过模板参数修改比较方法(如降序)[^4]: ```cpp set<int, greater<int>> mySet; // 降序存储 mySet.insert(42); mySet.insert(17); ``` #### 二、STL算法与模板 1. **排序算法`sort`** 结合`vector`和自定义比较函数实现灵活排序。 **示例**(按字符串长度排序): ```cpp #include <vector> #include <algorithm> vector<string> words = {"apple", "cpp", "algorithm"}; sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.size() < b.size(); }); ``` 2. **类模板与函数模板** **函数模板示例**(通用交换函数): ```cpp template <typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; } ``` **类模板示例**(实现栈)[^5]: ```cpp template <typename T> class Stack { private: vector<T> elements; public: void push(const T& elem) { elements.push_back(elem); } T pop() { T top = elements.back(); elements.pop_back(); return top; } }; ``` #### 三、性能优化技巧 1. **选择合适容器** - 需要快速插入/删除:`unordered_map`(哈希表实现) - 需要有序遍历:`map` - 需要去重集合:`set` 2. **避免不必要的拷贝** 使用引用或移动语义: ```cpp void process(const vector<int>& arr); // 通过常量引用传递 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值