模板与STL容器结合可实现泛型编程,提升代码复用性;2. 可编写模板函数操作任意STL容器,如通用打印函数;3. 类模板可包含STL容器成员,适配多种数据类型;4. 模板可与map等关联容器结合,实现如计数功能;5. 需注意类型操作支持、运算符重载及避免硬编码容器类型。

在C++中,模板与STL容器的结合使用是实现泛型编程的核心手段。通过模板,我们可以编写适用于多种数据类型的通用代码,而STL容器(如vector、list、map等)本身就是基于模板设计的,天然支持类型参数化。合理使用两者可以提升代码复用性和灵活性。
可以编写模板函数来处理不同类型的STL容器。关键是让函数接受模板参数,并使用迭代器进行通用访问。
示例:编写一个通用的打印函数,适用于任何支持迭代器的容器:
template <typename Container>
void printContainer(const Container& container) {
for (const auto& item : container) {
std::cout << item << " ";
}
std::cout << std::endl;
}
调用方式:
立即学习“C++免费学习笔记(深入)”;
std::vector<int> vec = {1, 2, 3};
std::list<double> lst = {1.1, 2.2, 3.3};
printContainer(vec); // 输出: 1 2 3
printContainer(lst); // 输出: 1.1 2.2 3.3
可以在类模板中使用STL容器作为成员变量,使类能适配多种数据类型。
template <typename T>
class DataStorage {
private:
std::vector<T> data;
public:
void add(const T& value) {
data.push_back(value);
}
void print() const {
for (const auto& item : data) {
std::cout << item << " ";
}
std::cout << std::endl;
}
};
使用示例:
DataStorage<std::string> strStore;
strStore.add("Hello");
strStore.add("World");
strStore.print(); // 输出: Hello World
STL中的map和set也是模板容器,可以与自定义模板逻辑配合使用。
例如,创建一个模板类用于统计任意类型键值的出现次数:
template <typename KeyType>
class Counter {
private:
std::map<KeyType, int> counts;
public:
void add(const KeyType& key) {
++counts[key];
}
int get(const KeyType& key) const {
auto it = counts.find(key);
return it != counts.end() ? it->second : 0;
}
};
使用:
Counter<std::string> wordCount;
wordCount.add("apple");
wordCount.add("apple");
std::cout << wordCount.get("apple") << std::endl; // 输出: 2
结合模板与STL时需注意以下几点:
基本上就这些。模板与STL的结合让C++具备强大的泛型能力,掌握它们的协作方式有助于写出简洁高效的代码。
以上就是C++模板与STL容器结合使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号