我有这个功能:
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
。但问题是,我不知道,它会是什么类型。它也可以是单string
或vector
<int>
/ <string>
。因此,当存在string
时,它只迭代一次,如果有一些向量,则迭代(myVector.count()-1)
- 次。如何使这种类型独立的迭代器?
答案 0 :(得分:2)
在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
答案 1 :(得分:1)
好的,我想我现在明白了你的问题。我认为你正在寻找某种类型的功能。这种东西。
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);
}