JosiP
JosiP

Reputation: 3079

access c++ stl map only using iterator

I want to have a class with map variable as a private variable:

class CTest{
private:
 std::map<int, int> m_map;
public:
 std::map<int int>::iterator get_iterator();
 void add(int key, int val) { m_map[key] = val; }
}

Is there any way that in function some_action() i can only using get_iterator() iterate over the map for example:

CTest c;

/* here i want to go through that m_map, but i cannot have access to it */
void some_actoin(){
 ???
}

int main(void){
  c.add(1, 1);
  c.add(2, 3);
  some_action();
}

regards J.

Upvotes: 0

Views: 1113

Answers (3)

ronag
ronag

Reputation: 51255

You need a "beginning" and an "end" to iterate over it.

e.g.

class CTest{
private:
 std::map<int, int> m_map;
public:
 std::map<int int>::const_iterator cbegin();
 std::map<int int>::const_iterator cend();
 void add(int key, int val) { m_map[key] = val; }
}

void some_actoin()
{
 for(std::map<int int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
 {
     const auto& val = *it;
 }

 // C++11
 for(const auto& val : c)
 {
 }
}

Upvotes: 1

alexrider
alexrider

Reputation: 4463

The short answer is no. You will need at least m_map.end() to end the loop. However I'd suggest instead of get_iterator() add something like for_each to your class that will accept std::function, and apply it to all elements in a map using std::for_each. This way your acton doesn't need even to know that it iterates map, it just does it's job.

Upvotes: 1

Jonathan Potter
Jonathan Potter

Reputation: 37132

If you really wanted to do this, you could add public methods to get the beginning and end iterators, e.g.

class CTest{
private:
    std::map<int, int> m_map;
public:
    std::map<int, int>::const_iterator cbegin() { return m_map.cbegin(); }
    std::map<int, int>::const_iterator cend() { return m_map.cend(); }
};

CTest c;

void some_action()
{
    for (std::map<int, int>::const_iterator it = c.cbegin(); it != c.cend(); ++it)
    {
        // do action
    }
}

Upvotes: 6

Related Questions