迭代器和模板
Iterator and templates
本文关键字:迭代器 更新时间:2023-10-16
我尝试操作迭代器。
template <typename Mytype>
class Myclass
{
public:
Myclass ( const Mytype & myarg)
{
this->data=myarg;
}
~Myclass ( void ){}
set<int> Test ( const Mytype & myarg ) const
{
set<int> result;
typename Mytype::iterator it=myarg.begin();
return result;
}
private:
//
mutable Mytype data;
};
此代码正在编译中。但当我想使用它时,它不再编译:这里有一个例子:
int main()
{
Myclass <string> t0 ( "caacaa" );
set<int> r=t0.Test("a");
return 0;
}
我现在得到一个错误:
test.cpp:在成员函数'std::set<int>我的类<Mytype>::Test(const Mytype&)const[带Mytype=std::basic_string<char>]':test.cpp:38:26:从这里实例化test.cpp:25:48:错误:从转换'std::basic_string<char>::const_iterator{aka__gnucxx::__normal_iterator<const char*,std::basic_string<char>>}"转换为非标量类型"std::basic_string<char>::迭代器__gnucxx::__normal_iterator<char*,std::basic_string<char>>}'请求
我试图弄清楚出了什么问题,但我不明白这个错误。
在const成员函数中,成员数据也是const。所以你需要使用const_iterator
:
typename Mytype::const_iterator it = myarg.begin();
因为myarg.begin()
返回常量迭代器,因为myarg
是常量,因为成员函数是常量。
更好地使用auto
:
auto it = myarg.begin();
但您仍然需要知道it
是常量—auto
有助于避免键入长名称,而不知道it
是常量。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?