![](/img/trans.png)
[英]How to properly deduce a dereferenced type of the iterator returned from std::set::begin()?
[英]Iterator type returned by set2.begin()
在一个quizz问题中,我认为以下程序无法编译,因为我期望迭代器类型set<int>::iterator
而不是set<int, int>::iterator
。
我可以在C ++ 98,C ++ 11和C ++ 14中成功编译以下程序,并打印结果9 5 4 3 2 1 0 0, 1, 2, 3, 4, 5, 9,
看来程序是正确的。
为什么迭代器类型set<int, int>::iterator
在该行上可以接受?
#include <iostream>
#include <set>
#include <vector>
#include <functional>
using namespace std;
int main(){
int mynumbers[] = { 3, 9, 0, 2, 1, 4, 5 };
vector<int> v(mynumbers, mynumbers+7);
set<int> set1(v.begin(),v.end());
set<int, greater<int> > set2(v.begin(), v.end());
//
// The following iterator type compiles. Why is that so ?
//
for(set<int, int>::iterator i=set2.begin();i!= set2.end(); i++)
cout<<*i<<" ";
for(set<int>::iterator i=set1.begin();i!= set1.end(); i++)
cout<<*i<<", ";
cout<<endl;
return 0;
}
为什么迭代器类型
set<int, int>::iterator
在该行上可以接受?
它不是。 int
不是比较器。 你违反了标准的要求。 该计划格式不正确。
有些编译器会更严格地检查这些要求。
供参考:正确的类型将set<int, greater<int> >::iterator
,或者对于C ++ 11及更高版本只是auto
。 set<int>::iterator
也是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.