STL练习题目
时间: 2025-05-11 19:29:16 浏览: 15
### C++ STL 练习题及答案
以下是基于引用内容设计的几道 C++ STL 练习题及其解答。
---
#### **练习题一:单词计数器**
**题目描述**: 使用 `std::map` 实现一个简单的单词计数器程序。给定一段文字,统计其中每个单词出现的次数并按字母顺序输出结果。
**解决方案**:
为了实现此功能,可以利用 `std::map` 来存储单词与其对应的频率,并通过遍历输入文本完成统计工作[^1]。
```cpp
#include <iostream>
#include <sstream>
#include <map>
#include <algorithm>
int main() {
std::string text;
getline(std::cin, text);
// 将所有字符转为小写以便统一处理
for(char& c : text){
c = tolower(c);
}
std::istringstream iss(text);
std::string word;
std::map<std::string, int> word_count;
while(iss >> word){
++word_count[word];
}
// 输出结果
for(const auto& pair : word_count){
std::cout << pair.first << ": " << pair.second << "\n";
}
return 0;
}
```
---
#### **练习题二:字符串去重**
**题目描述**: 利用 `std::set` 去除重复的字符串项。对于每一条指令,如果操作码为 `0`,表示插入新字符串;如果是 `1`,则查询当前是否存在指定字符串。
**解决方案**:
可以通过 `std::set` 自动去除重复元素的功能来简化逻辑[^2]。
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
set<string> st;
for(int i = 0; i < n; ++i){
int opt;
string word;
cin >> opt >> word;
if(opt == 0){
st.insert(word);
}else{
if(st.find(word) != st.end()){
cout << "Yes\n";
}else{
cout << "No\n";
}
}
}
return 0;
}
```
---
#### **练习题三:消息队列管理**
**题目描述**: 设计一个支持优先级的消息队列管理系统。当接收到 `"PUSH"` 指令时,需将带有特定优先级的消息存入队列;而接到 `"POP"` 指令时,则应弹出最高优先级的消息[^3]。
**解决方案**:
采用 `std::priority_queue` 结合自定义比较函数的方式能够高效解决此类问题。
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <string>
struct Message {
std::string data;
int priority;
};
// 定义大顶堆
struct Compare {
bool operator()(const Message& m1, const Message& m2) {
if(m1.priority != m2.priority)
return m1.priority < m2.priority;
return true; // 若优先级相同,默认保持原序即可
}
};
int main(){
std::priority_queue<Message, std::vector<Message>, Compare> pq;
std::string command;
while(getline(cin, command)){
if(command.substr(0,4) == "PUSH"){
size_t pos = command.find(' ');
std::string str = command.substr(pos+1,command.rfind(' ')-pos-1);
int pri = stoi(command.substr(command.rfind(' ')+1));
pq.push(Message{str,pri});
}
else if(command == "POP"){
if(pq.empty())
std::cout << "NULL!\n";
else{
std::cout << pq.top().data << '\n';
pq.pop();
}
}
}
return 0;
}
```
---
阅读全文
相关推荐




















