我有这个函数:
set<int> Search(const _Type & hayHeap) const {
set<int>myset;
for (vector<typename>::const_iterator i = needle.begin(); i != needle.end(); ++i) {
cout << (*i) << " ";
}
return myset;
};
针的定义如下:vector<string> needle;
现在我需要创建另一个迭代器,它将遍历hayHeap
。但问题是,我不知道它会是什么类型。它也可能是<int>
/<string>
中的单个string
或vector
。因此,当有一个string
时,它只迭代一次,如果有某个向量,它迭代(myVector.count()-1)
次。如何使这种类型独立的迭代器?
在C++03:中
template <typename C>
set<int> Search(const C& hayHeap) const {
set<int>myset;
for (typename C::const_iterator i = needle.begin(); i != needle.end(); ++i) {
cout << (*i) << " ";
}
return myset;
};
在C++11中:
template <typename C>
set<int> Search(const C& hayHeap) const {
set<int>myset;
for (auto& i : needle) {
cout << i << " ";
}
return myset;
};
根据您的实际需要,您可以将int
替换为typename C::value_type
好吧,我想我现在明白你的问题了。我认为你在寻找某种类型的函数。类似的东西。
template<typename T>
struct my_selector {
static void search(T& t) {
cout << " Single string / int search" << endl;
bool b = t == "needle";
cout << b;
}
};
template<typename T>
struct my_selector<vector<T>> {
static void search(vector<T>& needle) {
cout << " Vector search" << endl;
for (typename vector<T>::const_iterator i = needle.begin();
i != needle.end(); ++i)
{
cout << (*i) << " ";
}
}
};
int main() {
typedef std::vector<std::string> _Type;
_Type needle(4,"s");
// Search function is selected based on type of _Type.
my_selector<_Type>::search(needle);
// typedef string _Type;
// _Type needle = "needle";
// // Search function is selected based on type of _Type.
// my_selector<_Type>::search(needle);
}