c++ - 我可以将向下转换应用于迭代器吗?
问题描述
我需要知道我是否通过应用向下转换来向模板类发送正确类型的容器。
// C++ program to demonstrate input iterator
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v1 = { 1, 2, 3, 4, 5 };
// Declaring an iterator
vector<int>::iterator i1;
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
if(bi != nullptr)
cout << "Succesfull" << endl;
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
// Accessing elements using iterator
cout << (*i1) << " ";
}
return 0;
}
我得到错误:
prog.cpp: In function ‘int main()’:
prog.cpp:12:2: error: ‘bidirectional_iterator’ was not declared in this scope
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:27: error: ‘bi’ was not declared in this scope
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:45: error: ‘i1’ does not name a type
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:47: error: expected ‘>’ before ‘&’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:47: error: expected ‘(’ before ‘&’ token
prog.cpp:12:48: error: expected primary-expression before ‘>’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:53: error: expected ‘)’ before ‘;’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
无论如何我可以检查容器中迭代器的类型,以便我可以控制它是否会在模板类中传递?
解决方案
看起来您完全误解了标准库中的迭代器。首先,如果您发现自己在dynamic_cast
使用任何标准库类型(一个值得注意的例外 - he-he, pun - is std::exception
,也许还有一些我现在没有想到的其他类型),那么您做错了什么。绝大多数 STL 类型都不是多态的,因此永远不应该这样使用。
迭代器也是如此。您不需要强制std::vector::iterator
转换为biderectional_iterator
,而只需在需要此类迭代器的地方使用它。有iterator_traits
,当与向量迭代器一起使用时,将表明向量的迭代器是双向的iterator_category
。查看有关 iterator_traits的更多信息
trait 的美妙之处在于所有这些逻辑都是在编译时完成的,所以如果你试图在迭代器中使用它无法处理的场景,你最终会出现编译错误,并且可以立即修复程序。
推荐阅读
- python - Python提取文件名正则表达式的一部分
- c++ - 更快的镜像算法
- javascript - javascript中日期格式错误的格式
- angular - 找不到名称'keyof'
- android - 在 AOSP 7.1 中链接预建共享库时未定义的引用
- sparql - 如何按城市过滤结果?
- ios - 在原生 iOS 应用程序中集成响应式 html 网页并使用 Apache Cordova 进行通信
- ios - 我想在不让他们安装应用程序的情况下向用户的电话号码发送图片和消息。我正在使用 firebase 进行存储(swift iOS)
- scala - 除了反射之外,有没有办法在 Scala 中创建泛型类型的实例
- c++ - 在抛出 'std::invalid_argument' what() 实例后调用终止:leetcode 问题中的 stoi 错误