473,780 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unable to read from const std::map<>&

63 New Member
Actually I'm quite sure I've missed something trivial here, but I just can't find it.
Seemingly I cannot read from a const map&

I try

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5. void show ( 
  6.   const // troubling-const
  7.   map<char, double>& myconstmap )
  8. {
  9.   cout << "A->" << myconstmap['A'] << "\n";
  10. }
  11.  
  12. int main ()
  13. {
  14.   map<char, double> mymap;
  15.   mymap['A']=0.1;
  16. }
  17.  
  18.  
If I remove the troubling const I'm able to access it but I don'r really feel like giving up on const

I'm thankful for any hint
J
Nov 29 '07 #1
12 5837
weaknessforcats
9,208 Recognized Expert Moderator Expert
The const has nothing to do with it.

It's your use of operator[] in the the cout in line 9. That operator returns a reference to the map element. It's possible to change the map byusing this reference. Your const gets in the way of that and you get a compile error.

Either: a) don't use const or b) use const but don't use the map [] operator.
Nov 29 '07 #2
jabbah
63 New Member
The const has nothing to do with it.

It's your use of operator[] in the the cout in line 9. That operator returns a reference to the map element. It's possible to change the map byusing this reference. Your const gets in the way of that and you get a compile error.
ok

Either: a) don't use const
mhh, I dont really feel like this is a solution, but rather a workaround which I dont feel comfortable with. The map is created in one spot and I want to hand it around and read it from multiple places without the possibility to change it.


or b) use const but don't use the map [] operator.
But as far as I can see the only other way to access the elements in the map then is the const_iterator which is not suitable for me - I rather would need some kind of random access.

Well, ok thanks for your answer.
Maybe map is just not the right thing here - I'll look for something else.

Thanks.
Nov 29 '07 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Why insist on map::operator[] ???

You can use map::find() instead. That will return the pair that has your key and value.

Otherwise, you can write a new map iof your own be deriving from map (bs sure map has a virtual destructor) and then write an operator[] in your map that returns a const value for the key rather than a const_iterator.

Please note, access in a map is not random, like an array. Access is based on a key and not and element number. The map::operator[] tries to make the map look like an array but it does return the value in a form that allows you to change it.
Nov 29 '07 #4
jabbah
63 New Member
Why insist on map::operator[] ???

You can use map::find() instead. That will return the pair that has your key and value.
Because I dont want to do something in logarithmic time, when it should be done in constant time.

Otherwise, you can write a new map iof your own be deriving from map (bs sure map has a virtual destructor) and then write an operator[] in your map that returns a const value for the key rather than a const_iterator.
That sounds like a very interessting idea - I think I'll try that. Very interessting. I have never thought about deriving from some stl thing. mhh...


Please note, access in a map is not random, like an array. Access is based on a key and not and element number. The map::operator[] tries to make the map look like an array but it does return the value in a form that allows you to change it.
I don't get that. What I meant when I said random was that I can access an arbitrary element in constant time - independent of whether I'm allowed to change the element or not. And as I expect a map to be something like a hashtable and I know my keys will all be unique (Im not actually using char as indicated in my example but pointers to struct), I would expect [] to execute in constant time.
Although now that you made me think about it again I dont find any statement about execution time of [] in
http://www.cppreferenc e.com/cppmap/map_operators.h tml
Nov 29 '07 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
What I meant when I said random was that I can access an arbitrary element in constant time - independent of whether I'm allowed to change the element or not. And as I expect a map to be something like a hashtable and I know my keys will all be unique (Im not actually using char as indicated in my example but pointers to struct), I would expect [] to execute in constant time.
A map is a red-black binary tree. Access is not in constant time like an array.

All STL associative containers use red-black trees.

There is a hashmap but it is still non-standard.
Nov 30 '07 #6
jabbah
63 New Member
A map is a red-black binary tree. Access is not in constant time like an array.
Ok, I see. So the execution times of both, operator[] and find() are logarithmic, right?

I think, I'm going to put the map into a wrapper that provides something like
Expand|Select|Wrap|Line Numbers
  1. TYPE& operator[]( const key_type& key );
  2. const TYPE& operator[]( const key_type& key ) const;
Besides the satisfaction of my const-request this would allow me to change from map to whatever, maybe a hash table in the future.
Dec 3 '07 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
Yes, you could change the implementation of the tree.

Generally, I advise to not expose your implementation for that very reason. All of these STL containers should be fronted by an access class of your design and with your interface methods.

Ditto for memory using new and delete. I always use a Create/Delete function and bury the allocation.
Dec 3 '07 #8
jabbah
63 New Member
Thanks weaknessforcats
Dec 3 '07 #9
jabbah
63 New Member
Errr, Im afraid Im back .... I tried to:

you can write a new map iof your own be deriving from map (bs sure map has a virtual destructor) and then write an operator[] in your map that returns a const value for the key rather than a const_iterator.
like this:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5.  
  6. template < typename keytype, typename TYPE >
  7. class cmap: public std::map<keytype, TYPE> 
  8. {
  9. public:
  10.   virtual const TYPE& operator[](const keytype& k) const // this seems to keep me from accessing the non-const operator[]
  11.   //virtual const TYPE& get(const keytype& k) const 
  12.   {
  13.     // get rid of const so we are able to call operator[]()
  14.     const cmap<keytype,TYPE>& const_cmap = *this;
  15.     const std::map<keytype,TYPE>& const_map = const_cmap;
  16.     std::map<keytype,TYPE>& nonconst_map = const_cast < std::map<keytype,TYPE>& > ( const_map );
  17.     // retrieve the element and return it as const&
  18.     return nonconst_map[k];
  19.   }
  20.  
  21.   virtual ~cmap(){}
  22. };
  23.  
  24.  
  25.  
  26. int main (){
  27.  
  28.   cmap <char, double> mycmap;
  29.   mycmap['A'] = 0.2; // compile-error: "assignment of read-only location"
  30.  
  31.   const cmap<char, double>& const_mycmap = mycmap;
  32.   cout << const_mycmap['A'] << "\n";
  33.   //cout << const_mycmap.get('A') << "\n";
  34. }
This doesnt compile due to line 29, so seemingly I do have a const operator[] now, but the non-const operator[] is gone.

If I exchange line 15 with 16 and 37 with 38 it works, but well then there is still no const operator[]() const.
Dec 6 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
6591
by: Mark Van Orman | last post by:
Hi all, I have an application that logs in xml. Assume <xmlLog></xmlLog>. In this element the app logs anything it gets from foreign hosts. Now if the host sends xml data, the structure of the document changes. ie. <xmlLog><somTag></somTag></xmlLog>. This will cause problems with my log reader, because it assumes that <xmlLog/> contains non-xml data.
5
4335
by: Evgeny | last post by:
Hi, all! I try to convert my existing code written in VC6 to VC7 and have some problem with stl auto pointer template. class CColumn; #include <memory> typedef auto_ptr<CMyBase> CMyBasePtr; class CMyBase {
6
4902
by: scottyman | last post by:
I can't make this script work properly. I've gone as far as I can with it and the rest is out of my ability. I can do some html editing but I'm lost in the Java world. The script at the bottom of the html page controls the form fields that are required. It doesn't function like it's supposed to and I can leave all the fields blank and it still submits the form. Also I can't get it to transfer the file in the upload section. The file name...
3
2399
by: asclearuc | last post by:
Hello Is it possible to use map<string&, string&>? Why I need it. I have a large amount of data obtained from XML file. I should do processing of this data. The processing takes many stages, and could be done using std::map templates. But new instance of std::map is required on each stage.
3
1722
by: markoj | last post by:
hi i HAVE WRITTEN A perl script that will search a file and print output I have created a simple html doc i want to be able to click a link and it will print the output in of a specific file so i need the perl script to read a file 1-15 depending on the input from the html #!c:\perl\bin\perl.exe use warnings; use strict; print <<HTTPHDR;
0
1417
by: subramanian100in | last post by:
consider the following program: #include <cstdlib> #include <iostream> #include <map> #include <utility> #include <string> using namespace std;
0
3738
by: TrevRex | last post by:
Hello, I work for a non-profit in San Diego as a GIS Specialist. I have had to teach myself about some scripting to create some dynamic maps, but I am still very limited in my skills, so I have had to explore the internet in order to discover various tutorials and examples that have led me on a positive path. Right now I am working on a Google Mash-Up that will incorporate over 14,000 records, which will appear as separate markers that...
0
10306
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
10139
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
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7485
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
5373
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...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
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.