C++ Primer(第5版) 练习 16.64
练习 16.64 为上一题中的模板编写特例化版本来处理vector<const char*>。编写程序使用这个特例化版本。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
#include <iostream>
#include <vector>
#include <cstring>
template <typename T>
int countOccurrences(const std::vector<T>& vec, const T& value){
int count = 0;
for(const auto& element : vec){
if(element == value){
count++;
}
}
return count;
}
template <>
int countOccurrences<const char*>(const std::vector<const char*>& vec, const char* const& value){
int count = 0;
for(const auto& element : vec){
if (std::strcmp(element, value) == 0){
count++;
}
}
return count;
}
int main(){
std::vector<const char*> charPtrVec = {"apple", "banana", "apple", "cherry", "apple"};
int charPtrCount = countOccurrences(charPtrVec, "apple");
std::cout<< "\"apple\" appears "<<charPtrCount<<" times in charPtrVec."<<std::endl;
return 0;
}