Rog*_*and 9 c++ stl visual-c++ visual-studio-2012
我有一个std::map,我想在第二个条目开始迭代.
我可以解决这个问题,但我很困惑为什么"明显的"语法不能编译.错误消息没有帮助,因为它引用std::string,我在这里没有使用.
这是一些代码
// Suppose I have some map ...
std::map<int, int> pSomeMap;
// This is fine ...
std::map<int, int>::const_iterator pIterOne = pSomeMap.begin();
++pIterOne;
// This doesn't compile ...
std::map<int, int>::const_iterator pIterTwo = pSomeMap.begin() + 1;
Run Code Online (Sandbox Code Playgroud)
VS2012在上面的行中给出以下错误
错误C2784:'std :: _ String_iterator <_Mystr> std :: operator +(_ String_iterator <_Mystr> :: difference_type,std :: _ String_iterator <_Mystr>)':无法推断'std :: _ String_iterator <_Mystr>'的模板参数来自'int'
谁能解释一下这里发生了什么?
Pla*_*aHH 16
std::map<T>::iterator是迭代器类的双向迭代器.那些只有++和--运营商.+N并且[]仅适用于随机访问迭代器(可以在例如中找到std::vector<T>).
这背后的原因是添加N到随机访问迭代器是恒定时间(例如添加N*sizeof(T)到a T*),而对双向迭代器执行相同的操作则需要应用++ N时间.
你能做什么(如果你有C++ 11)是:
std::map<int, int>::const_iterator pIterTwo = std::next(pSomeMap.begin(),1);
Run Code Online (Sandbox Code Playgroud)
这对所有迭代器类型都是正确的.
std::map迭代器是双向的,因此它们只提供++和 - 运算符,但不提供operator+,即使它是+1.如果你真的需要模拟operator +,
你可以使用std::advance,但这会导致为迭代器调用增量序列.
| 归档时间: |
|
| 查看次数: |
7338 次 |
| 最近记录: |