473,396 Members | 1,998 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

std::map

2 questions:

Given a map defined as

std::map<int,string> stringmap;

//How do you access the data_type (string) via an iterator?

std::string spoo("doh");

stringmap.insert(std::make_pair(1,spoo));
// I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;
But this doesn't compile with error that the operator+ has not been defined
....
I think the problem is that the iterator returns a pair. Is it possible to
do this?

I know I can do:
if(stringmap.find(1) != stringmap.end()) std::cout << stringmap[1];
2nd question:

This doesn't work with BCB6 (causes a compile error about casting a pair to
an int???)

//stringmap is defined as a private class member
const std::string classname::getstring(size_t index) const { return
stringmap[index];}

but this compiles fine and seems to work with no problems:

const std::string classname::getstring(size_t index) { return
stringmap[index];}

Is this correct? Why can I not define this function as const? It's not
changing any
member data.

Thanks.

Jul 19 '05 #1
24 17243
Duane Hebert wrote:
// I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;
std::cout << it->second;

should do the trick.

Btw I recommend that you use a const_iterator instead of an
iterator.

I know I can do:
if(stringmap.find(1) != stringmap.end()) std::cout << stringmap[1];
Brr, this is terribly inefficient. Why dont you store the
returnvalue of find?

if((it = stringmap.find(1)) != stringmap.end())
std::cout << it->second;

2nd question:

This doesn't work with BCB6 (causes a compile error about casting a pair to
an int???)

//stringmap is defined as a private class member
const std::string classname::getstring(size_t index) const { return
stringmap[index];}

but this compiles fine and seems to work with no problems:

const std::string classname::getstring(size_t index) { return
stringmap[index];}

Is this correct? Why can I not define this function as const? It's not
changing any member data.


Because operator[] is not const. It might change the
contents of your stringmap. The map is const in this
function, so you are not allowed to call it.

Use find instead.

hope this helps,

Christoph

Jul 19 '05 #2
Duane Hebert wrote in news:YY******************@wagner.videotron.net:
2 questions:

Given a map defined as

std::map<int,string> stringmap;

//How do you access the data_type (string) via an iterator?

std::string spoo("doh");

stringmap.insert(std::make_pair(1,spoo));
// I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;
Change this to it->second; if you want the key do it->first.


But this doesn't compile with error that the operator+ has not been
defined ...
I think the problem is that the iterator returns a pair. Is it
possible to do this?

I know I can do:
if(stringmap.find(1) != stringmap.end()) std::cout <<
stringmap[1];


This should work fine stringmap[i] should return a std::string &
2nd question:

This doesn't work with BCB6 (causes a compile error about casting a
pair to an int???)
I don't really understand this, maybe you should post a complete
example that doesen't compile.

//stringmap is defined as a private class member
const std::string classname::getstring(size_t index) const { return
stringmap[index];}

A return of std::string const & would be more effecient here.

but this compiles fine and seems to work with no problems:

const std::string classname::getstring(size_t index) { return
stringmap[index];}

Is this correct? Why can I not define this function as const? It's
not changing any
member data.


Yes this is correct std::map<>::operator[] is not defined as a
const-member function, this is because the non-const version
will insert a new element into the map if it doesn't exist.

std::string classname::getstring( int index ) const
{
std::map<int,string>::iterator ptr =
stringmap.find( index )
:

if ( ptr != stringmap.end() ) return ptr->second;

// return std::string( "< some default>" );
//throw std::runtime_error( "Item Not Found" );

// the choice is your's.
}
HTH

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #3
> > const std::string classname::getstring(size_t index) { return
stringmap[index];}

Is this correct? Why can I not define this function as const? It's not
changing any member data.


Because operator[] is not const. It might change the
contents of your stringmap. The map is const in this
function, so you are not allowed to call it.


But why doesn't map define a const operator[] in addition to the non const
one?
Jul 19 '05 #4
> > But why doesn't map define a const operator[] in addition to the non
const
one?

What would it do if the key was not present in the map?


Errrr...do nothing and return a reference to NULL :)
Jul 19 '05 #5

"Duane Hebert" <sp**@flarn.com> wrote in message
news:YY******************@wagner.videotron.net...
2 questions:

Given a map defined as

std::map<int,string> stringmap;

//How do you access the data_type (string) via an iterator?

std::string spoo("doh");

stringmap.insert(std::make_pair(1,spoo));
// I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;


So you've figured out that you need to insert pairs, so the thing in the map
that the iterator is pointing to is a pair. You also said you want only the
string, not the whole pair. *it would be the whole pair. In a pair, there
is a "first" and "second". You want to point to the "second".
Jul 19 '05 #6

"Smeckler" <sm*********@hotSPAMmail.com> wrote in message
news:bj*******************@news.demon.co.uk...
But why doesn't map define a const operator[] in addition to the non const one?

What would it do if the key was not present in the map?


Errrr...do nothing and return a reference to NULL :)

And how do you return a _reference_ to NULL?

Chris
Jul 19 '05 #7

"Chris Theis" <Ch*************@nospam.cern.ch> wrote in message news:bj**********@sunnews.cern.ch...

"Smeckler" <sm*********@hotSPAMmail.com> wrote in message
news:bj*******************@news.demon.co.uk...
> But why doesn't map define a const operator[] in addition to the non

const
> one?
>
What would it do if the key was not present in the map?


Errrr...do nothing and return a reference to NULL :)

And how do you return a _reference_ to NULL?

That was a joke, son. (Didn't you see the smilely?)
Jul 19 '05 #8
> > // I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;
Change this to it->second; if you want the key do it->first.


Thanks. I stumbled on that myself. I also found that
std::cout (*it).second; works as well. This was what I tried
originally but I missed the () .

I know I can do:
if(stringmap.find(1) != stringmap.end()) std::cout <<
stringmap[1];


This should work fine stringmap[i] should return a std::string &


That's correct but if I want to access each element of the map with a for
loop
it requires that I know the min and max keys and try all of them. That's
why
I wanted to get the iterator to work. (also to figure it out :-)

//stringmap is defined as a private class member
const std::string classname::getstring(size_t index) const { return
stringmap[index];}


A return of std::string const & would be more effecient here.


but this compiles fine and seems to work with no problems:

const std::string classname::getstring(size_t index) { return
stringmap[index];}

Is this correct? Why can I not define this function as const? It's
not changing any
member data.


Yes this is correct std::map<>::operator[] is not defined as a
const-member function, this is because the non-const version
will insert a new element into the map if it doesn't exist.

std::string classname::getstring( int index ) const
{
std::map<int,string>::iterator ptr =
stringmap.find( index )
:

if ( ptr != stringmap.end() ) return ptr->second;


This didn't exactly work on my compiler. Threw the same error as before.
I had to make ptr a const_iterator,
then it worked fine. Not sure why since find() returns an iterator,
but thanks for the help.
HTH


It does. Thanks.
Jul 19 '05 #9
Duane Hebert wrote:
std::string classname::getstring( int index ) const
{
std::map<int,string>::iterator ptr =
stringmap.find( index )
:

if ( ptr != stringmap.end() ) return ptr->second;


This didn't exactly work on my compiler. Threw the same error as before.
I had to make ptr a const_iterator,
then it worked fine. Not sure why since find() returns an iterator,
but thanks for the help.


No, because the stringmap is const in this function find
returns a const_iterator in this case.

Christoph

Jul 19 '05 #10
Duane Hebert wrote in news:Ii*******************@wagner.videotron.net:
std::string classname::getstring( int index ) const
{
std::map<int,string>::iterator ptr =
stringmap.find( index )
:

if ( ptr != stringmap.end() ) return ptr->second;


This didn't exactly work on my compiler. Threw the same error as
before. I had to make ptr a const_iterator,
then it worked fine. Not sure why since find() returns an iterator,
but thanks for the help.


My code was wrong, but fortunatly your compiler cought the error.

Since this is a const member function the member stingmap is
effectivly constant within it so stringmap.find( index ) is calling
std::map<>::find( Key ) const, which returns a const_iterator.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #11
> My code was wrong, but fortunatly your compiler cought the error.

Since this is a const member function the member stingmap is
effectivly constant within it so stringmap.find( index ) is calling
std::map<>::find( Key ) const, which returns a const_iterator.


Borland 's BCB6 uses StlPort which seems to be pretty compliant and
less buggy than the RogueWave implementations of previous editions.
The help for the stl containers is not the best though. I'll be getting a
couple of books soon.
Jul 19 '05 #12
> > // I tried this:
for(std::map<int,string> ::iterator it = stringmap.begin(); it !=
stringmap.end(); ++it)
std::cout << *it;
So you've figured out that you need to insert pairs, so the thing in the

map that the iterator is pointing to is a pair. You also said you want only the string, not the whole pair. *it would be the whole pair. In a pair, there is a "first" and "second". You want to point to the "second".


Right but *it.second doesn't work. (second is not a member of iterator)
This was my problem. I could create a
pair from *it and it would work. I didn't realize that there are two
operators
in the line *it.second, the . and the * and the . has precedence. So this
line
turns into *(it.second).
One solution would be to do it->first since it returns a reference.
I don't like this because I think that it obscures the fact that *it is a
reference.
The solution that I was looking for was simply (*it).second.

The answers that I received here were very helpful. std::map is different
from containers
like vectors and sets in that it contains another "container".
Jul 19 '05 #13
Duane Hebert wrote:

Duane, look at the formatting of your messages. Are you hitting <enter>
at the end of your lines or something? Please don't do that. Set your
news client's line wrap to a reasonable length (around 72 is good) and
let it do the wrapping.

Right but *it.second doesn't work. (second is not a member of iterator)
This was my problem. I could create a
pair from *it and it would work. I didn't realize that there are two
operators
in the line *it.second, the . and the * and the . has precedence. So this
line
turns into *(it.second).
One solution would be to do it->first since it returns a reference.
I don't like this because I think that it obscures the fact that *it is a
reference.


It absolutely does not. Every C & C++ programmer recognizes immediately
that a->b means (*a).b. If anything the 'arrow' syntax is less confusing.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #14
"Chris Theis" <Ch*************@nospam.cern.ch> wrote in message
news:bj**********@sunnews.cern.ch...

"Smeckler" <sm*********@hotSPAMmail.com> wrote in message
news:bj*******************@news.demon.co.uk...
> But why doesn't map define a const operator[] in addition to the non

const
> one?
>
What would it do if the key was not present in the map?


Errrr...do nothing and return a reference to NULL :)

And how do you return a _reference_ to NULL?

Chris


Easy. And, since this is the STL we're talking about, why not create a
handy template function :)

template <typename TypeName> TypeName& GetNullReference()
{
return *(TypeName*)NULL;
}
Jul 19 '05 #15

"Duane Hebert" <sp**@flarn.com> wrote in message
news:ns******************@weber.videotron.net...

So you've figured out that you need to insert pairs, so the thing in the map
that the iterator is pointing to is a pair. You also said you want only

the
string, not the whole pair. *it would be the whole pair. In a pair,

there
is a "first" and "second". You want to point to the "second".


Right but *it.second doesn't work.


So?
One solution would be to do it->first since it returns a reference.
I don't like this because I think that it obscures the fact that *it is a
reference.
The solution that I was looking for was simply (*it).second.


Yuck. Why would you want to muck it up like that? it->second is perfectly
natural. I think it's crazy to say pointer notation "obscures" the fact
that the dereferenced pointer is a reference. That's like saying you prefer
the statement "It's false that I don't like pie" to the statement "I like
pie." because the second sentence obscures the fact that you don't dislike
it.
Jul 19 '05 #16
"Smeckler" <sm*********@hotSPAMmail.com> writes:
[snip]
Easy. And, since this is the STL we're talking about, why not create a
handy template function :)

template <typename TypeName> TypeName& GetNullReference()
{
return *(TypeName*)NULL;
}


This has undefined behavior.
Jul 19 '05 #17
Smeckler wrote:

Easy. And, since this is the STL we're talking about, why not create a
handy template function :)

template <typename TypeName> TypeName& GetNullReference()
{
return *(TypeName*)NULL;
}


I hope you are joking. If not, you need to learn some C++.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #18
> Yuck. Why would you want to muck it up like that? it->second is
perfectly
natural. I think it's crazy to say pointer notation "obscures" the fact
that the dereferenced pointer is a reference. That's like saying you prefer the statement "It's false that I don't like pie" to the statement "I like
pie." because the second sentence obscures the fact that you don't dislike
it.


I prefer to use the dot operator when referencing an object that's not a
pointer. It's
a matter of taste and not worth an argument. Both ways work. To me, it
wasn't intuitive
that (*it).first would work. But to answer your simile, I guess that it's
not true that I do
agree with you :-)
Jul 19 '05 #19
> > Easy. And, since this is the STL we're talking about, why not create a
handy template function :)

template <typename TypeName> TypeName& GetNullReference()
{
return *(TypeName*)NULL;
}


I hope you are joking. If not, you need to learn some C++.

-Kevin

Kevin,

Would you care to be more specific about your objection to my code?


Jul 19 '05 #20
Smeckler wrote:
Would you care to be more specific about your objection to my code?


First, this has undefined behaviour. (Dereferencing a 0 Pointer)

Second, how do you test the returned reference for 0??
You cannot. So somebody ends up with a dangling reference. And probably
crashes a while later when he tries to use it...

Christoph

Jul 19 '05 #21
On Tue, 9 Sep 2003 10:20:27 +0100, "Smeckler"
<sm*********@hotSPAMmail.com> wrote:
> Easy. And, since this is the STL we're talking about, why not create a
> handy template function :)
>
> template <typename TypeName> TypeName& GetNullReference()
> {
> return *(TypeName*)NULL;
> }
>
>


I hope you are joking. If not, you need to learn some C++.

-Kevin

Kevin,

Would you care to be more specific about your objection to my code?


It has undefined behaviour. Dereferencing a null pointer is always a
bug. In other words, in the language spec, there is no such thing as a
null reference, since in order to create one, you have to go outside
the language spec.

In practice, the code will crash on some platforms, while on others it
will return what you think of as a "null reference".

Tom
Jul 19 '05 #22

"Duane Hebert" <sp**@flarn.com> wrote in message
news:I_*******************@weber.videotron.net...

I prefer to use the dot operator when referencing an object that's not a
pointer. It's
a matter of taste and not worth an argument. Both ways work. To me, it
wasn't intuitive
that (*it).first would work.


The whole point is it's supposed to look like a pointer. Otherwise, you
wouldn't have to go around your elbow to get to your butt to dereference it,
thereby forcing it to look like a reference just because that's how you want
it to look.
Jul 19 '05 #23

"Duane Hebert" <sp**@flarn.com> wrote in message
news:I_*******************@weber.videotron.net...

I prefer to use the dot operator when referencing an object that's not a
pointer. It's
a matter of taste and not worth an argument. Both ways work. To me, it
wasn't intuitive
that (*it).first would work.


Or to put it another way, if it were just a regular reference object, you
would access it like
it.
instead of like
(*it).
So it's not just a matter of preference in this case, it's a matte of how
the thing was designed to be used - i.e., like a pointer.
Jul 19 '05 #24
Smeckler wrote:
Easy. And, since this is the STL we're talking about, why not create a
handy template function :)

template <typename TypeName> TypeName& GetNullReference()
{
return *(TypeName*)NULL;
}


I hope you are joking. If not, you need to learn some C++.

-Kevin


Kevin,

Would you care to be more specific about your objection to my code?


I could, but I think I'll let Herb Sutter do it instead:

http://www.gotw.ca/conv/002.htm

To summarize: You cannot have a null reference. You cannot dereference a
null pointer, under any circumstances.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #25

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Woodster | last post by:
I have declared the following std::map<std::string, std::string> myMap; to pass myMap to functions should I be declaring functions as: void function(std::map<std::string, std::string>); ...
1
by: Antti Granqvist | last post by:
Hello! I have following object relations: Competition 1--* Category 1--* Course 1 | | * Course
2
by: Serengeti | last post by:
Hello, in my class I have a map that translates strings to pointers to some member functions. The code goes like this: class F { typedef void (Function::*MathFuncPtr)(); std::map<std::string,...
1
by: Saeed Amrollahi | last post by:
Dear All C++ Programmers Hello I am Saeed Amrollahi. I am a software engineer in Tehran Sewerage Company. I try to use std::map and map::find member function. I use Visual Studio .NET. my...
19
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
3
by: Dan Trowbridge | last post by:
Hi everyone, In my attempt to port code from VS 6.0 to VS.NET I had some code break along the way, mostly due to not adhereing closely to the C++ standard. This may be another instance but I...
1
by: Avery Fong | last post by:
The following program will result in a compile error when building under Debug but will compile under Release. Why does is work under Release mode but not under Debug This program is developed...
13
by: kamaraj80 | last post by:
Hi I am using the std:: map as following. typedef struct _SeatRowCols { long nSeatRow; unsigned char ucSeatLetter; }SeatRowCols; typedef struct _NetData
2
by: digz | last post by:
Hi, I am trying to write a program which has two threads one of them write to a map , and the other one deletes entries based on a certain criterion.. first I cannot get the delete portion to...
8
by: mveygman | last post by:
Hi, I am writing code that is using std::map and having a bit of an issue with its performance. It appears that the std::map is significantly slower searching for an element then a sequential...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.