如何遍历未知类型
How to iterate through an unknown type?
我有这个函数:
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);
}
相关文章:
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 即使直接从官方示例中复制,也找不到未知类型名称QML_ELEMENT和 QML 模块
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 线程 std::调用未知类型,无法专门化函数错误
- MacOS 上的 LLVM - 标准文件 iosfwd 中未知类型名称'template'
- C++ 未知类型名称,即使类型是通过标头定义的
- 通过模板函数对未知类型调用方法
- 错误:使用 SWIG 的未知类型名称"类"
- C++:将未知类型的对象存储为成员变量的类
- 为什么未知类型名称"Complejo"?
- 在 Mac OS x 中制造期间出现错误未知类型名称"constexpr"
- 查找上下文RPC_NS_HANDLE未知类型名称
- 错误:未知类型名称"功能跟踪"
- C++中的自由定理:模板是否本质上对未知类型的对象无知和中立?
- 未知 使用用于C++代码的标头编译 C 代码时char16_t未知类型名称
- Linux中未知类型名称UINT64_T和UINT16_T UINT8_T
- 如何确定未知类型数组的索引是否为空
- 当我返回节点*时,C++中出现未知类型错误
- 无法编译任何C++程序;错误:未知类型名称'uint8_t'