I've just started to code in C++, so i'm new to STL .
Here i'm trying to iterate over a graph stored as vector of vectors.
#include <iostream>
#include <vector>
#include <iostream>
using namespace std;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*it) << endl;
if ((*it) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;
}
}
return 0;
}
int main()
{
}
I'm getting an error std::vector<int> is not derived from const gnu cxx. Can someone point me in the right direction ?
*it pointing to vector not int that is why you are getting error
following code may work for you
#include <vector>
#include <iostream>
using namespace std;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*(*it).begin()) << endl;
if (( (*(*it).begin())) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;
}
}
return 0;
}
int main()
{
}
for accessing first element of the vector of the use
(*(*it).begin()) in place of (*it)
if you are studying graph then use array of vector. for more details please go through following url
C++ Depth First Search (DFS) Implementation
cout << (*it) << endl;
Here, you declared it as a:
vector<vector<int> >::iterator it;
Therefore, *it is a:
vector<int>
So you are attempting to use operator<< to send it to std::cout. This, obviously, will not work. This is equivalent to:
vector<int> v;
cout << v;
There is no operator<< overload that's defined for what cout is, and a vector<int>. As you know, in order to print the contents of a vector, you have to iterate over its individual values, and print its individual values.
So, whatever your intentions were, when you wrote:
cout << (*it) << endl;
you will need to do something else, keeping in mind that *it here is an entire vector<int>. Perhaps your intent is to iterate over the vector and print each int in the vector, but you're already doing it later.
Similarly:
if ((*it) == x)
This won't work either. As explained, *it is a vector<int>, which cannot be compared to a plain int.
It is not clear what your intentions are here. "Graph stored as a vector or vectors" is too vague.
The following code compiles with the option std=c++11. But x is missing in vector<vector<int>>. If adj had type vector<pair<int, vector<int>>> it would better match.
The following code compiles for vector<vector<int>> but it doesn't use x.
using std::vector;
using std::pair;
using std::cout;
using std::endl;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for(it=adj.begin();it!=adj.end();it++)
{
// cout << (*it) << endl;
for (const auto& nexts: *it)
cout << nexts << ' ';
cout << endl;
for(i=(*it).begin();i!=(*it).end();i++)
{
cout << (*i) << endl;
if((*i)==y)
return 1;
}
}
return 0;
}
This code compiles with <vector<pair<int, vector<int>>> and uses x.
using std::vector;
using std::pair;
using std::cout;
using std::endl;
int reach(vector<pair<int, vector<int> > > &adj, int x, int y) {
vector<pair<int, vector<int> > >::iterator it;
vector<int>::iterator i;
for(it=adj.begin();it!=adj.end();it++)
{
cout << it->first << endl;
if (it->first == x)
for(i=it->second.begin();i!=it->second.end();i++)
{
cout << (*i) << endl;
if((*i)==y)
return 1;
}
}
return 0;
}
Wrap it up in an iterator.
This can be templated for reuse.
Here is a minimal working example for the std::vector<T> container:
#include <iostream>
#include <utility>
#include <vector>
/// Iterable vector of vectors
/// (This just provides `begin` and `end for `Vector2Iterable<T>::Iterator`).
template<typename T>
class VovIterable
{
public:
static const std::vector<T> EMPTY_VECTOR;
/// Actual iterator
class Iterator
{
typename std::vector<std::vector<T>>::const_iterator _a1;
typename std::vector<T>::const_iterator _a2;
typename std::vector<std::vector<T>>::const_iterator _end;
public:
/// \param a1 Outer iterator
/// \param a2 Inner iterator
/// \param end End of outer iterator
explicit Iterator(typename std::vector<std::vector<T>>::const_iterator a1, typename std::vector<T>::const_iterator a2, typename std::vector<std::vector<T>>::const_iterator end)
: _a1(a1)
, _a2(a2)
, _end(end)
{
Check();
}
bool operator!=(const Iterator &b) const
{
return _a1 != b._a1 || _a2 != b._a2;
}
Iterator &operator++()
{
++_a2; // Increment secondary
Check();
return *this;
}
const T &operator*() const
{
return *_a2;
}
private:
void Check()
{
while (true)
{
if (_a2 != _a1->end()) // Is secondary live?
{
break;
}
// Increment primary
_a1++;
if (_a1 == _end) // Is primary dead?
{
_a2 = EMPTY_VECTOR.end();
break;
}
_a2 = _a1->begin(); // Reset secondary
}
}
};
private:
std::vector<std::vector<T>> _source;
public:
explicit VovIterable(std::vector<std::vector<T>> source)
: _source(std::move(source))
{
}
/// Start of vector of vectors
[[nodiscard]] Iterator begin() const
{
if (this->_source.empty())
{
return end();
}
return Iterator(this->_source.cbegin(), this->_source.cbegin()->cbegin(), this->_source.cend());
}
/// End of vector of vectors
[[nodiscard]] Iterator end() const
{
return Iterator(this->_source.cend(), EMPTY_VECTOR.end(), this->_source.cend());
}
};
template<typename T>
const std::vector<T> VovIterable<T>::EMPTY_VECTOR = {0};
/// Sample usage
int main()
{
std::vector<std::vector<int>> myVov{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i: VovIterable(myVov))
{
std::cout << i << std::endl;
}
return 0;
}
Related
I am trying to solve a question on leetcode which is finding the top k frequent elements. I think my code is correct but the output for a test case is failing.
Input: [ 4,1,-1,2,-1,2,3]
K=2
My answer comes out to be {1,-1} but the expected is {-1,2}. I am not sure where am i getting wrong.
struct myComp{
constexpr bool operator()(pair<int,int> & a,pair<int,int> &b)
const noexcept
{
if(a.second==b.second)
{
return a.first<b.first;
}
return a.second<b.second;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mp;
for(int i=0;i<nums.size();i++)
{
mp[nums[i]]++;
}
priority_queue<pair<int,int>,vector<pair<int,int>>,myComp> minheap;
for(auto x:mp)
{
minheap.push(make_pair(x.second,x.first));
if(minheap.size()>k)
{
minheap.pop();
}
}
vector<int> x;
while(minheap.size()>0)
{
x.push_back(minheap.top().second);
minheap.pop();
}
return x;
link: https://leetcode.com/problems/top-k-frequent-elements
In the minheap, pairs of <frequency, element> are being pushed. Since we want to sort these pairs on basis of frequency, we need to compare on the basis of frequency only.
Let's say there are two pairs a and b. Then for normal sorting, the comparison would be :
a.first < b.first;
And for reverse sorting, the comparison would be :
a.first > b.first;
In case of min-heap, we need reverse sorting. Hence, the following comparator makes your code pass all the test cases :
struct myComp
{
constexpr bool operator()(pair<int,int> & a,pair<int,int> &b)
const noexcept
{
return a.first > b.first;
}
};
There are several issues with your code.
Obviously there is somewhere using namespace std; in your code. This should be avoided. You will find many posts here on SO explaining, why it this should not be done.
Then we need to qualify all elements from the std library with std::, which makes the scope very clear.
Next: You do not need your own sorting function. Since you insert the elements from the pair in swapped order into the std::priority_queue, the sorting criteria is valid for the counter part, not for the key value. So, your sorting function was anyway wrong, because it was sorting accodring to "second" and not to "first". But if we have a standard sorting, we do not need a special sorting algorithm. A std::pair has a less-than operator. So, the definition can be simply:
std::priority_queue<std::pair<int, int>> minheap;
Then, your if statement
if(minheap.size()>k)
{
minheap.pop();
}
is wrong. You will allow only k values to be inserted. And this are not necessarily the biggest ones. So, you need to insert all values from the std::unordered map. And then they are sorted.
With some cosmetic changes the code will look like the below:
#include <iostream>
#include <utility>
#include <unordered_map>
#include <vector>
#include <queue>
std::vector<int> topKFrequent(std::vector<int>& nums, size_t k) {
std::unordered_map<int, int> mp;
for (size_t i = 0; i < nums.size(); i++)
{
mp[nums[i]]++;
}
std::priority_queue<std::pair<int, int>> minheap;
for (auto x : mp)
{
minheap.push(std::make_pair(x.second, x.first));
}
std::vector<int> x;
for (size_t i{}; i< k; ++i)
{
x.push_back(minheap.top().second);
minheap.pop();
}
return x;
}
int main() {
std::vector data{ 4,1,-1,2,-1,2,3 };
std::vector result = topKFrequent(data, 2);
for (const int i : result) std::cout << i << ' '; std::cout << '\n';
return 0;
}
An additional solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <utility>
auto topKFrequent(std::vector<int>& nums, size_t k) {
// Count occurences
std::unordered_map<int, size_t> counter{};
for (const int& i : nums) counter[i]++;
// For storing the top k
std::vector<std::pair<int, size_t>> top(k);
// Get top k
std::partial_sort_copy(counter.begin(), counter.end(), top.begin(), top.end(),
[](const std::pair<int, size_t >& p1, const std::pair<int, size_t>& p2) { return p1.second > p2.second; });
return top;
}
// Test code
int main() {
std::vector data{ 4,1,-1,2,-1,2,3 };
for (const auto& p : topKFrequent(data, 2))
std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
return 0;
}
And of course, we do have also the universal solution for any kind of iterable container. Including the definition for type traits using SFINAE and checking for the correct template parameter.
#include <iostream>
#include <utility>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <iterator>
#include <type_traits>
// Helper for type trait We want to identify an iterable container ----------------------------------------------------
template <typename Container>
auto isIterableHelper(int) -> decltype (
std::begin(std::declval<Container&>()) != std::end(std::declval<Container&>()), // begin/end and operator !=
++std::declval<decltype(std::begin(std::declval<Container&>()))&>(), // operator ++
void(*std::begin(std::declval<Container&>())), // operator*
void(), // Handle potential operator ,
std::true_type{});
template <typename T>
std::false_type isIterableHelper(...);
// The type trait -----------------------------------------------------------------------------------------------------
template <typename Container>
using is_iterable = decltype(isIterableHelper<Container>(0));
// Some Alias names for later easier reading --------------------------------------------------------------------------
template <typename Container>
using ValueType = std::decay_t<decltype(*std::begin(std::declval<Container&>()))>;
template <typename Container>
using Pair = std::pair<ValueType<Container>, size_t>;
template <typename Container>
using Counter = std::unordered_map<ValueType<Container>, size_t>;
// Function to get the k most frequent elements used in any Container ------------------------------------------------
template <class Container>
auto topKFrequent(const Container& data, size_t k) {
if constexpr (is_iterable<Container>::value) {
// Count all occurences of data
Counter<Container> counter{};
for (const auto& d : data) counter[d]++;
// For storing the top k
std::vector<Pair<Container>> top(k);
// Get top k
std::partial_sort_copy(counter.begin(), counter.end(), top.begin(), top.end(),
[](const std::pair<int, size_t >& p1, const std::pair<int, size_t>& p2) { return p1.second > p2.second; });
return top;
}
else
return data;
}
int main() {
std::vector testVector{ 1,2,2,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,6,7 };
for (const auto& p : topKFrequent(testVector, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
double cStyleArray[] = { 1.1, 2.2, 2.2, 3.3, 3.3, 3.3 };
for (const auto& p : topKFrequent(cStyleArray, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
std::string s{"abbcccddddeeeeeffffffggggggg"};
for (const auto& p : topKFrequent(s, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
double value = 12.34;
std::cout << topKFrequent(value,2) << "\n";
return 0;
}
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
I have a question about iterators on lists. In function I have to compare the doubles, but I don't know how to get the elements from the second level, with only iterators to the first level.
void function (std::list<std::list <double>>::iterator *begin, std::list<std::list <double>>::iterator *end)
{
//do something
}
int main()
{
std::list <std::list <double>> a_list;
function (a_list.begin(), a_list.end());
}
void function (list<list <double> >::iterator begin, list<list <double> >::iterator end)
{
for(std::list<std::list <double> >::iterator it =begin;it!= end;it++)
{
for(std::list <double>:: iterator it_inner = (*it).begin(); it_inner != (*it).end();it_inner++)
{
printf("%f ",*it_inner );
}
printf("\n");
}
}
int main()
{
std::list <std::list <double> > a_list;
for(int i=0;i<=3;i++)
{
std::list <double> inner_list;
for(double j=0;j<=8;j+=2.2)
{
inner_list.push_back(j);
}
a_list.push_back(inner_list);
}
function (a_list.begin(), a_list.end());
}
You can pass the iterators as parameters or just the entire list, like this:
#include <iostream>
#include <list>
using namespace std;
void funcA (list<list<double>>::iterator begin, list<list<double>>::iterator end) {
//do something
list<double>::iterator sublist1 = begin->begin();
cout << *sublist1 + 1 << endl;
}
void funcB (list<list<double>> list) {
for (auto&& sublist: list) {
for (auto&& value: sublist) {
cout << value << ' ';
}
}
cout << endl;
}
int main() {
list <list<double>> a_list = {{1,2,3},{4,5,6}};
// list<list<double>>::iterator a = a_list.begin();
// list<double>::iterator b = a->begin();
//
// cout << *b + 2 << endl;
funcA(a_list.begin() , a_list.end());
funcB(a_list);
}
I have a TreeVertex class:
// TreeVertex.h
#ifndef __TREEVERTEX__
#define __TREEVERTEX__
#include <list>
using namespace std;
class TreeVertex {
public:
TreeVertex(list<int>, TreeVertex* = NULL);
list<int> getItemset();
private:
list<int> Itemset;
TreeVertex * Parent;
TreeVertex * LeftChild;
TreeVertex * RightSibling;
};
#endif // __TREEVERTEX__
// TreeVertex.cpp
#include "TreeVertex.h"
TreeVertex::TreeVertex(list<int> Itemset, TreeVertex* Parent) : Itemset(Itemset), Parent(Parent), LeftChild(NULL),
RightSibling(NULL) { }
list<int>
TreeVertex::getItemset() {
return Itemset;
}
And a main function like this:
#include <iostream>
#include "TreeVertex.h"
using namespace std;
int main (int argc, const char ** const argv)
{
list<int> tmpList1;
tmpList1.push_back(1);
TreeVertex * tmpTreeVert1 = new TreeVertex(tmpList1);
list<int> tmpList2;
tmpList2.push_back(2);
TreeVertex * tmpTreeVert2 = new TreeVertex(tmpList2);
list<int> newVertItemset;
newVertItemset.push_back(tmpTreeVert1->getItemset().front());
newVertItemset.push_back(tmpTreeVert2->getItemset().front());
cout << newVertItemset.front() << " " << newVertItemset.back() << endl;
TreeVertex * newTreeVert = new TreeVertex(newVertItemset);
cout << newTreeVert->getItemset().front() << " " << newTreeVert->getItemset().back() << endl;
for (list<int>::iterator it = newTreeVert->getItemset().begin(); it != newTreeVert->getItemset().end(); ++it) {
cout << (*it) << " ";
}
cout << endl;
cout << newTreeVert->getItemset().size() << endl;
return 0;
}
The output looks like this:
1 2
1 2
2
2
The next to the last output (the first single "2"), should be "1 2" just like the others.
Any ideas why the iterator is not going over the first element?
Thanks.
The problem with this:
list<int>
TreeVertex::getItemset() {
return Itemset;
}
Everytime you call this function, it returns a copy of the object, which means the following loop should not work:
for (list<int>::iterator it = newTreeVert->getItemset().begin();
it != newTreeVert->getItemset().end(); ++it) {
as it compares iterators from two different objects. A solution is to return reference as:
list<int> & //<--- return reference, not copy
TreeVertex::getItemset() {
return Itemset;
}
But a better solution is to remove getItemset altogether and instead of that, add begin() and end() member functions as:
//define these typedefs first in the public section
typedef list<int>::iterator iterator;
typedef list<int>::const_iterator const_iterator;
iterator begin() { return itemSet.begin(); }
iterator end() { return itemSet.end(); }
and then write the for loop as:
for(TreeVertex::iterator it = newTreeVert->begin();
it != newTreeVert->end(); ++it) {
If you can use C++11, then you should add these:
//note : the function names start with `c`
const_iterator cbegin() const { return itemSet.cbegin(); }
const_iterator cend() const { return itemSet.cend(); }
Or, if you use C++03 (and cannot use C++11), then add these:
const_iterator begin() const { return itemSet.begin(); }
const_iterator end() const { return itemSet.end(); }
The problem lies within the block:
check_sort(l.begin(), l.end(), "list");
time_insert(insert_list, data);
check_sort(s.begin(), s.end(), "set");
time_insert(insert_set, data);
check_sort(v.begin(), v.end(), "vector");
time_insert(insert_vector, data);
The error states that the variables are not declared in the scope, but shouldn't l,s,v be universal variables here? What am I doing wrong.
#include <cmath>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <vector>
#include <ctime>
#include <list>
#include <set>
#include <algorithm>
#include <cstdlib>
using namespace std;
typedef void Inserter(vector<double>);
vector<double> gen_data(int num_elts);
void insert_list(vector<double> data);
void insert_set(vector<double> data);
void insert_vector(vector<double> data);
void time_insert( Inserter inserter, vector<double> data);
template <class Iter> bool is_sorted(Iter first, Iter last);
template <class Iter> void check_sort(Iter first, Iter last, string cont_kind);
int main() {
srand(time(0));// initialize random number generator
cout << "How many elements for container? ";
int num_elts = 0;
while (cin >> num_elts) {
if (num_elts <= 0)
cout << "Error, should be > 1";
else {
vector<double> data = gen_data(num_elts);
check_sort(l.begin(), l.end(), "list");
time_insert(insert_list, data);
check_sort(s.begin(), s.end(), "set");
time_insert(insert_set, data);
check_sort(v.begin(), v.end(), "vector");
time_insert(insert_vector, data);
}
cout << "\nHow many elements for next container? ";
}
return 0;
}
void time_insert( Inserter inserter, vector<double> data) {
clock_t t1 = clock();
if (t1 == clock_t(-1)) { //if clock() doesn’t work
cerr << "sorry, no clock\n";
exit(1);
}
inserter(data);
clock_t t2 = clock();
if (t2 == clock_t(-1)) {
cerr << "sorry, clock overflow\n";
exit(2);
}
cout << "Elapsed time: " << fixed << setprecision(2)
<< double(t2-t1)/CLOCKS_PER_SEC << " seconds\n";
}
class Larger_than {
double v;
public:
Larger_than(double vv) : v(vv){}
bool operator()(double x) const {return x>v;}
};
// Sorts and then inserts data into a list
void insert_list(vector<double> data)
{
list<double> l;
for(int i=0; i < data.size(); i++){
list<double>::iterator p = find_if(l.begin(),l.end(), Larger_than(data[i]));
l.insert(p, data[i]);
}
}
// Sorts and then inserts data into a list
void insert_set(vector<double> data)
{
set<double> s;
for(int i=0; i < data.size(); i++){
set<double>::iterator p = find_if(s.begin(),s.end(), Larger_than(data[i]
));
s.insert(p, data[i]);
}
}
// Sorts and then inserts data into a list
void insert_vector(vector<double> data)
{
vector<double> v;
for(int i=0; i < data.size(); i++){
vector<double>::iterator p = find_if(v.begin(),v.end(), Larger_than(data
[i]));
v.insert(p, data[i]);
}
}
// generate num_elts random numbers in the range [0.0, 1.0),
// which are returned in a vector
vector<double> gen_data (int num_elts)
{
vector<double> result;
for (int i = 0; i < num_elts; i++) {
double datum = 1.0*rand()/RAND_MAX;
result.push_back(datum);
}
return result;
}
// is container spanned by [from, last) sorted?
template <class Iter> bool is_sorted(Iter first, Iter last)
{
Iter next = first; // next element
for (next++; next != last; next++, first++) {
if (*first > *next)
return false;
}
return true;
}
// prints a msg describing container kind, as well as whether container
// spanned by [from, last) is sorted
template <class Iter> void check_sort(Iter first, Iter last, string cont_kind)
{
cout << "Check: " << cont_kind << " is ";
if (!is_sorted(first, last)) cout << "not ";
cout << "sorted\n";
}
How should main know about s, l and v at all? They're local variables of completely unrelated functions (the insert_xxx ones), there's no way main could know about them. If you want to make them globally accessible, just make them global variables, i.e., put their definition before main:
// ...
list<double> l;
set<double> s;
vector<double> v;
int main(){
// ....
}
// ...
It looks like l is defined in the 'insert_list' function and would not available in main. Only variables defined insider your function are available.
You don't appear to have declared the variables at all. Why do you think they should exist in main? There are no globals or locals with those names anywhere that I can see. Try declaring them before using them.
I've made a method to scroll/wrap around a map of items, so that if the end is reached, the method returns the first item and vice-versa.
Is there more succinct way of doing this?
MyMap::const_iterator it = myMap.find(myKey);
if (it == myMap.end())
return 0;
if (forward) {
it++;
if (it == myMap.end()) {
it = myMap.begin();
}
} else {
if (it == myMap.begin()) {
it = myMap.end();
}
it--;
}
You could implement the wrap-around behavior directly into a new iterator-class - templated to be a wrapper for some actual iterator, that supplies a more elegant interface to the caller (so that its increment and decrement operators do the wrap-around automatically).
Also - be careful of the empty container. You don't want to "wrap-around" when there are no elements in the container.
You can do this with a template. As was stated by a previous poster, this can be cumbersome from the standpoint that it never reaches the end so the user must somehow control this. I'm assuming you have a good reason, perhaps producing some round robin behavior.
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
using namespace std;
template <class T>
class ScrollIterator
{
public:
ScrollIterator(T &myCtr, typename T::iterator pos)
:ctr(myCtr),
it(pos)
{
}
ScrollIterator operator++()
{
if (++it == ctr.end()) { it = ctr.begin(); }
return *this;
}
bool operator!=(const ScrollIterator &rhs) const
{
return (this->it != rhs.it);
}
bool operator!=(const typename T::const_iterator &rhsIT) const
{
return (this->it != rhsIT);
}
typename T::value_type operator*() const
{
return *it;
}
private:
T &ctr;
typename T::iterator it;
};
int main (int argc, char *argv[])
{
vector<int> v;
v.push_back(2);
v.push_back(3);
v.push_back(5);
v.push_back(7);
int i = 0;
for (ScrollIterator<vector<int> > it(v,v.begin()); it != v.end() && i < 10; ++i, ++it)
{
cout << "Vector = " << i << " Value: " << *it << "\n";
}
set<string> s;
s.insert("c");
s.insert("a");
s.insert("b");
i = 0;
for (ScrollIterator<set<string> > it(s,s.begin()); it != s.end() && i < 10; ++i, ++it)
{
cout << "Set = " << i << " Value: " << *it << "\n";
}
map<string, int> y;
y["z"] = 10;
y["y"] = 20;
y["x"] = 30;
i = 0;
for (ScrollIterator<map<string, int> > it(y,y.begin()); it != y.end() && i < 10; ++i, ++it)
{
cout << "Map = " << i << " Iterator: " << (*it).first << " = " << (*it).second << "\n";
}
return 1;
}
You can use upper_bound and lower_bound. For example:
if (myMap.empty()) return 0;
MyMap::const_iterator it;
if (forward) {
it = myMap.upper_bound(myKey);
if (it == myMap.end()) it = myMap.begin();
} else {
it = myMap.lower_bound(myKey);
if (it == myMap.begin()) it = myMap.end();
--it;
}
This will also behave differently if "myKey" doesn't exist in the map. It will take up from where the key would have been rather than going to the end or the beginning.
You could implement a cyclical iterator.
This is a difficult design. If reaching the "end" wraps around to the "beginning", how do you represent an empty container? The wraparound idea models an infinite sequence or a ring, but without a means to detect whether the iterator is still pointing to a valid position.
This problem is reminiscent of attempts to write a variable-sized ring buffer (such as a queue) without using a "dummy entry": How does one distinguish an empty ring from a full ring? Storing a base position and a size is only appropriate for random-access storage (as opposed to linked nodes), and is less amenable to locking optimization than pointer or index pairs.