简体   繁体   中英

Inserting next value in vector to map using iterator

I want to add the next and previous elements from a vector to a map. I thought I could do this using the iterator, but the following code doesn't work for me. Could someone please explain how this might be done and what my mistake was. Thank you.

 90  for ( it = vec.begin(); it != vec.end(); it++)
 91     {
 92         int Flag1 = vec.front();
 93         int Flag2 = vec.back();
 94 
 95         if( *it == Flag1)
 96             mymap[*it].insert(*(it++)); // Add next element
 97         else if( *it == Flag2 )
 98             mymap[*it].insert(*(it--)); // Add previous element
 99         else
100         {
101             mymap[*it].insert(*(it--)); // Add previous element
102             mymap[*it].insert(*(it++)); // Add next element
103         }
104     }

You don't want to be moving your iterator around in this loop (which both it++ and ++it would do!), you just want to get the next and the previous. With C++11, we have those in a simple function call:

std::next(it);
std::prev(it);

Pre-C++11, you can write them easily:

template <typename It> It next(It it) { std::advance(it, 1); return it; }
template <typename It> It prev(It it) { std::advance(it, -1); return it; }

So adding the next and previous elements would look like:

mymap[*it].insert(*next(it));
mymap[*it].insert(*prev(it));

Note that you're checking not whether the iterators are at the beginning or end but rather their values. This could be problematic if you have repeated values. Prefer instead to compare to the beginning and the end:

if (it == vec.begin()) {
   // only add next
   mymap[*it].insert(*next(it));
}
else if (next(it) == vec.end()) {
   // only add prev
   mymap[*it].insert(*prev(it));
}
else {
    // add both
   mymap[*it].insert(*next(it));
   mymap[*it].insert(*prev(it));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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