STL: Maps instance with the operator=

A

Alden Pierre

Hello,

I'm trying to understand why the following syntax is not allowed while
learning about maps. I've provided a snippet of the code I'm working
with. My gcc compiler does not like m_pos =m.begin();

m_pos is StringIntMap::iterator;
-----------------------------------------------------------------------------
#include <iostream>
#include <vector>
#include <string>
#include <map>

using std::vector;
using std::map;
using std::string;
using std::iterator;
using std::cout;

typedef map<string,int> StringIntMap;

vector< map<string,int>::const_iterator > val_count(
const map<string,int>&m, int val );

int main( void )
{
StringIntMap myMap;
vector< StringIntMap::const_iterator > myVec;

// inserting some elements
myMap["USA"] = 100;
myMap["Canada"] = 200;
myMap["Russia"] = 300;
myMap["Japan"] = 400;
myMap["Germany"]= 500;
myMap["China"] = 600;
myMap["India"] = 700;
myMap["Italy"] = 800;

myVec =val_count( myMap, 500 );

return 0;
}

vector< map<string,int>::const_iterator > val_count(
const map<string,int> & m, int val )
{
vector< map<string,int>::const_iterator >v_pos;
StringIntMap::iterator m_pos;

// why can't I do this?
m_pos =m.begin();

// will do some other stuff
return v_pos;
}
 
A

Andrew Koenig

vector< map<string,int>::const_iterator > val_count(
const map<string,int> & m, int val )
{
vector< map<string,int>::const_iterator >v_pos;
StringIntMap::iterator m_pos;

// why can't I do this?
m_pos =m.begin();

// will do some other stuff
return v_pos;
}

You can't write

m_pos = m.begin();

because you could then write

*m_pos = /* something or other */;

and doing so would change the contents of m, which you promised not to
change when you declared it as const.

So you need to change the definition of m_pos to

StringIntMap::const_iterator m_pos;

and then you should be fine.
 
A

Alden Pierre

Andrew said:
You can't write

m_pos = m.begin();

because you could then write

*m_pos = /* something or other */;

and doing so would change the contents of m, which you promised not to
change when you declared it as const.

So you need to change the definition of m_pos to

StringIntMap::const_iterator m_pos;

and then you should be fine.
Ah, that makes sense. Thank you very much.

Regards,
Alden
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top