简体   繁体   English

检查迭代器的最后一个元素

[英]check for the last element of an iterator

I have for loop like below: 我有如下的for循环:

for (multimap<string,string>::iterator it2 = ppp.first;it2 != ppp.second; ++it2)
   {
       if(it2==ppp.second -1)
       str=str+it2->second.substr(0,(it2->second).find('-'));
       else
       str=str+it2->second.substr(0,(it2->second).find('-'))+'&';
   }

I am using the condition like below: 我正在使用如下条件:

  if(it2==ppp.second -1)

for checking the last element and do some additional functionality if i found the last element.But the above condition doesnt work. 用于检查最后一个元素,并在我找到最后一个元素时做一些附加功能。但是上述条件不起作用。 it throw's me an error: 它抛出了我一个错误:

"000001.cc", line 50: Error: The operation "__rwstd::__rb_tree<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, __rwstd::__select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::basic_string<char, std::char_traits<char>, std::allocator<char>>>>>::iterator - int" is illegal.
1 Error(s) detected.

Could anybody please help. 任何人都可以帮忙。

You have not posted the whole code fragment so I am not sure what ppp is but I believe it is something like a pair of iterators. 您尚未发布整个代码片段,因此我不确定ppp是什么,但我相信它就像一对迭代器。 The iterator for map does not define the operator-(int val), so you can not use that one. map的迭代器未定义operator-(int val),因此您不能使用该迭代器。 However you can fix the error doing something like this: 但是,您可以执行以下操作来修复错误:

multimap<string,string>::iterator end_val = ppp.second;
--end_val;
for (multimap<string,string>::iterator it2 = ppp.first;it2 != ppp.second; ++it2)
{
    if(it2==end_val)
    str=str+it2->second.substr(0,(it2->second).find('-'));
    else
    str=str+it2->second.substr(0,(it2->second).find('-'))+'&';
}

Hope that helps. 希望能有所帮助。

Try 尝试

end = ppp.second;
std::advance (end, -1);
if (it2 == end) {}

Assuming ppp is the multimap, you should get the iterator to the first element by 假设ppp是多图,则应通过以下方式将迭代器添加到第一个元素

ppp.begin() 

or 要么

ppp.rbegin() // to get a reverse iterator

In you loop: 在您的循环中:

multimap<string,string>::iterator it2 = ppp.first

pp.first will not give the an iterator, instead it will give the first element of the pair helper class pair<string, string> pp.first将不提供迭代器,而是将提供pair助手类pair<string, string>的第一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM