473,671 Members | 2,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[STL] [Maps] operator[]

Hi, i have seen that this operator returns a reference to TYPE and not
a const reference.

I have a problem and I can't solve it:
i have a properties class with a get_property(co nst string &) function
that is const due to the fact that this method doesn't change the
"content" of properties class. If I write the method as this:
const string& get_property(co nst string& key) const {
return all_prop[key];
}

i receive an error in compile. The only way I have found to solve this
is to define class member all_prop as mutable. Is it correct? Is there
another way for coding this?
Thanks to all
Bye

--
Roberto Simoni

Oct 22 '06 #1
6 1721
r.simoni wrote:
>
i receive an error in compile. The only way I have found to solve this
is to define class member all_prop as mutable. Is it correct? Is there
another way for coding this?
Thanks to all
There is no map operator[] that is const. The problem is the
definition of the operator modifies the map if there isn't
already a pair in the map that matches.

It's clunky but you can do:

const string& get_property(co nst string& key) const {
map::<string, string>::conost _iterator it = all_props.find( key);
if(it != all_props.end() )
return (*it).second;
else
return string();
}
Oct 22 '06 #2
r.simoni wrote:
Hi, i have seen that this operator returns a reference to TYPE and not
a const reference.

I have a problem and I can't solve it:
i have a properties class with a get_property(co nst string &) function
that is const due to the fact that this method doesn't change the
"content" of properties class. If I write the method as this:
const string& get_property(co nst string& key) const {
return all_prop[key];
}

i receive an error in compile. The only way I have found to solve this
is to define class member all_prop as mutable. Is it correct?
Your problem is that std::map doesn't have a const operator[]. The way
that operator[] is defined by the standard can modify the map itself.
Is there
another way for coding this?
You need to use the find() function:

const string& get_property(co nst string& key) const
{
std::map<string ,string>::const _iterator i = all_prop.find(k ey);
return (i == all_prop.end()) ?string():i->second;
}

--
Clark S. Cox III
cl*******@gmail .com
Oct 22 '06 #3
LR
r.simoni wrote:
const string& get_property(co nst string& key) const {
return all_prop[key];
}

i receive an error in compile. The only way I have found to solve this
is to define class member all_prop as mutable. Is it correct? Is there
another way for coding this?

// asumming that...
typedef std::map<std::s tring,std::stri ng AllPropertiesMa p;
// and
AllPropertiesMa p all_prop;
// then
const std::string &get_property(c onst std::string &key) const {
AllPropertiesMa p::const_iterat or i = all_prop.find(k ey);
if(i != all_prop.end()) return i->second;
//
// here you have some options.
// you could return a const static local
// you could throw
// maybe something else
}

Generally, I think that I would prefer:

static const std::string &bad_propert y() {
static const std::string bp = "Bad Property";
return bp;
}

const std::string &get_property(c onst std::string &key) const {
AllPropertiesMa p::const_iterat or i = all_prop.find(k ey);
return i != all_prop.end() ? i->second : bad_property();
}

But undoubtedly, YMWV according to the requirements of your application.

HTH

LR
Oct 22 '06 #4
LR
Ron Natalie wrote:

const string& get_property(co nst string& key) const {
map::<string, string>::conost _iterator it = all_props.find( key);
if(it != all_props.end() )
return (*it).second;
else
return string();
^^^^^^^^
Can you please tell me what the life time of the temp object in the
above return statement is?

TIA
}
LR
Oct 22 '06 #5
LR wrote:
Ron Natalie wrote:

> const string& get_property(co nst string& key) const {
map::<string, string>::conost _iterator it = all_props.find( key);
if(it != all_props.end() )
return (*it).second;
else
return string();
^^^^^^^^
Can you please tell me what the life time of the temp object in the
above return statement is?

Oops, you're right. I forgot the thing was a returning
a reference. Bad thing. I originally just had a comment
there since it wasn't clear what the original poster wanted
to do in that case.

Oct 22 '06 #6

Ron Natalie ha scritto:
LR wrote:
Ron Natalie wrote:

const string& get_property(co nst string& key) const {
map::<string, string>::conost _iterator it = all_props.find( key);
if(it != all_props.end() )
return (*it).second;
else
return string();
^^^^^^^^
Can you please tell me what the life time of the temp object in the
above return statement is?
Oops, you're right. I forgot the thing was a returning
a reference. Bad thing. I originally just had a comment
there since it wasn't clear what the original poster wanted
to do in that case.
Thanks to all.
The problem is that in my book, I don't have a well organized section
for STL. So i don't remember that to use a map in "constant mode" i
have to use a const_iterator
Thanks

Oct 23 '06 #7

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

Similar topics

3
12691
by: Michael H Lees | last post by:
Hi there, I'm trying to use an stl map where I have my own defined (templated) class as a key. I have the class "variableId" below which I want to use as the key for an stl map. It has two members agent and slot. I've defined the < operator but I'm slightly confused, here's the complete class anyhow, template <typename agentId, typename slotId> class variableId
4
2720
by: Tom | last post by:
Hi, I need some help with stl maps. I am using a std::map that is sorted in a very special way. Therefore I am using my own sort function. That works fine. But this is only half the problem. Additionally "map.find()" should use a different comparison function. My map is like: map < myString, Whatever>
4
19951
by: Daniel Heiserer | last post by:
Hello, I used a unique associative container such as: //--------------- map<vector<int>,double> X; //--------------- In general I fill X with millions of entries. Sorting plays no role for me. All I need is uniqueness
6
8758
by: cylin | last post by:
Dear all, If I declared a map<int,string> MapA; How can I sort MapA by its data,i.e. string. for example: map<int,string> MapA; MapA=string("ccc"); MapA=string("bbb"); MapA=string("ddd");
4
2452
by: M?rio Amado Alves | last post by:
Will you help an outsider trying to trace the current state of persistent object technology? "I expect that there will be persistent object stores with STL-conforming interfaces fitting into the STL framework within the next year." --Alexander Stepanov, 1995 Has this happened? (In 1996 or another year.)
0
2058
by: Mona | last post by:
Newbie question - I am a newbie to c++ and stl maps. My question is based onSystemC which is a specialized C++ hardware programming language. I am trying to create a map with key of type sc_lv<22> (sc_logic vector with 22 bits) and the value is a class pf packets with 8 different fields of type sc_lv also. Here's what I am trying to do - cur_transactions_p current_pkt_info;
5
1778
by: DrLex | last post by:
This is a really annoying thing to look up in Google because all pages that mention STL maps or vectors will most likely also contain the word "template". So maybe this question has been asked before, but it's nearly impossible to find. I'm having trouble using STL vectors, maps, ... in templated functions, when the templated class is a template parameter of the map too. Below is a (cannibalized) example of a class 'Model' which contains...
18
2944
by: Hunk | last post by:
Would like some advice on the fillowing I have a sorted list of items on which i require to search and retrieve the said item and also modify an item based on its identity. I think an Map stl container would be most suited. Am i correct in my assumptions Problem Reocrds are already stored with a unique identity in a binary format.The structure is roughly ----------------------
3
2222
by: mahaveer | last post by:
Hi , I am facing a strange problem with STL maps ,I am using gdb to debug my debug my code. Upto one point the number of entries in the map is shown as follows , $79 = {_M_t = { _M_impl = {<std::allocator<std::_Rb_tree_node<std::pair<const long unsigned int, SessionContainer*> > >> = {<__gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<const long unsigned int, SessionContainer*> > >> = {<No data fields>}, <No data fields>},...
19
3519
by: C++Liliput | last post by:
I have a custom String class that contains an embedded char* member. The copy constructor, assignment operator etc. are all correctly defined. I need to create a map of my string (say a class called MyString) and an integer i.e. std::map<MyString, int>. Whenever I insert the elements in the map using the subscript operator, I noticed that the copy constructor for MyString is invoked more number of times than if I do it using the insert()...
0
8392
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8912
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8819
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8669
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5692
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4222
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2049
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1807
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.