473,466 Members | 1,639 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

The issue of const maps and operator[]

Hello.

Searching around before posting this message revealed that the issue has
been brought up a significant number of times (here are two related
threads [1] [2]). So /std::map<>/ does not provide a const version of
its /operator[]/ member function because that function is supposed to
modify the map in case the passed key is not present. The question which
follows is: why not provide a const overload which would throw when the
given key would not exist? It seems like a natural and easy-to-implement
solution which would contribute to map's associative array role.

In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision. Could anyone provide some information
(comments, links, etc.) on this?

[1] http://groups.google.com/groups?hl=e...9ed558c&rnum=1
[2] http://groups.google.com/groups?hl=e...f8b22d0&rnum=5

Thank you very much,

--
Ney André de Mello Zunino

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #1
6 1533
Ney André de Mello Zunino wrote:
Hello.

Searching around before posting this message revealed that the issue has
been brought up a significant number of times (here are two related
threads [1] [2]). So /std::map<>/ does not provide a const version of
its /operator[]/ member function because that function is supposed to
modify the map in case the passed key is not present. The question which
follows is: why not provide a const overload which would throw when the
given key would not exist?
Because it would violate the important principle that adding
const to code should not change its behaviour (except for
propogation of constness to other code), although it may
cause it to no longer compile. The language doesn't enforce
that in isolation; good library design is also necessary.
It seems like a natural and easy-to-implement
solution which would contribute to map's associative array role.
But it's too fragile, for the reason above.
In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision.


I find it enormously unlikely that this would be changed in the
next revision of C++.

-- James

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #2
Ney André de Mello Zunino wrote:
Hello.

Searching around before posting this message revealed that the issue has been brought up a significant number of times (here are two related
threads [1] [2]). So /std::map<>/ does not provide a const version of its /operator[]/ member function because that function is supposed to modify the map in case the passed key is not present. The question which follows is: why not provide a const overload which would throw when the given key would not exist? It seems like a natural and easy-to-implement solution which would contribute to map's associative array role.


C++ is powerful enough to make this an optional accessory, so it cannot
be used "by accident".

You can write a general wrapper for any map like this:

template <class M>
class const_map
{
const M &imp;

public:
const_map(const M &m) : imp(m) {}

const typename M::value_type::second_type &
operator[](const typename M::key_type &k) const
{
typename M::const_iterator f = imp.find(k);
if (f == imp.end())
throw std::range_error("Not found");

return f->second;
}
};

It can be used as the argument type for a function that only needs to
look up items, and needs throwing semantics for items it can't find.
When a "naked" map is passed to such a function, the compiler
automatically wraps it in a temporary wrapper to impose those
semantics.

// details of a person
typedef std::map<std::string, std::string> person;

// function that wants read-only/throw semantics
void foo(const const_map<person> &p)
{
std::cout << p["name"] << std::endl;
std::cout << p["address"] << std::endl;
std::cout << p["phone"] << std::endl;
}

int main(int argc, char *argv[])
{
try
{
person p;

p["name"] = "Santa";
p["address"] = "North pole";

foo(p);
}
catch (std::exception &e)
{
std::cout << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}

$ g++ cmap.cpp
$ ./a.out
Santa
North pole
Error: Not found

Jul 22 '05 #3
"James Dennett" <jd******@acm.org> wrote in message
news:YWxrd.191852$hj.44035@fed1read07...
In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision.


|I find it enormously unlikely that this would be changed in the
|next revision of C++.

yes true. but we are already looking into adding

T& map<K,T>::at( const Key& );
const T& map<K,T>::at( const Key& ) const;

which should throw if nothing is found.
Alternatively, I guess we could use operator()().

-Thorsten
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #4
Thorsten Ottosen wrote:
"James Dennett" <jd******@acm.org> wrote in message
news:YWxrd.191852$hj.44035@fed1read07...

In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision.

|I find it enormously unlikely that this would be changed in the
|next revision of C++.

yes true. but we are already looking into adding

T& map<K,T>::at( const Key& );
const T& map<K,T>::at( const Key& ) const;


This is reasonable and somewhat consistent with the at
member in other standard library class templates.
which should throw if nothing is found.
Alternatively, I guess we could use operator()().


I wouldn't like that:
mymap[1] = 3;
and
mymap(1) = 3;
would then both be valid, with different semantics in
the case mymap.find(1) == mymap.end(); and identical
semantics otherwise, but they look too similar. Let's
be consistent, and use "at" when we mean range-checked
access which throws if an element is absent.

-- James

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #5
On Fri, 3 Dec 2004 02:54:24 GMT, ne*****@cs.auc.dk ("Thorsten
Ottosen") wrote:
"James Dennett" <jd******@acm.org> wrote in message
news:YWxrd.191852$hj.44035@fed1read07...
In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision.
|I find it enormously unlikely that this would be changed in the
|next revision of C++.

yes true. but we are already looking into adding

T& map<K,T>::at( const Key& );
const T& map<K,T>::at( const Key& ) const;

which should throw if nothing is found.


I like the symmetry with vector::at.
Alternatively, I guess we could use operator()().


I don't like that, since operator() hasn't been used like that
elsewhere and is usually used for functors.

Tom

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #6
If anything is done to "operator[]", it should be given
the same syntax as "operator()", so we can have classes that
support multiple subscripts. Inconsistently,

foo(a,b)

is a two-argument call, but

foo[a,b]

is an invocation of the comma operator followed by a
one-argument call. One of the more obscure features
of the language.

John Nagle
Animats

Tom Widmer wrote:
On Fri, 3 Dec 2004 02:54:24 GMT, ne*****@cs.auc.dk ("Thorsten
Ottosen") wrote:

"James Dennett" <jd******@acm.org> wrote in message
news:YWxrd.191852$hj.44035@fed1read07...

In spite of having found several discussions on this topic, I could not
find mention of whether this issue is going to be addressed when C++
gets its next major revision.


|I find it enormously unlikely that this would be changed in the
|next revision of C++.

yes true. but we are already looking into adding

T& map<K,T>::at( const Key& );
const T& map<K,T>::at( const Key& ) const;

which should throw if nothing is found.

I like the symmetry with vector::at.

Alternatively, I guess we could use operator()().

I don't like that, since operator() hasn't been used like that
elsewhere and is usually used for functors.

Tom

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Jul 22 '05 #7

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

Similar topics

3
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...
12
by: Christof Krueger | last post by:
Hello, I'm quite new to C++ so maybe there's something I miss. I write a simple board game. It has a board class. This class has a method that returns the count of pieces a player has on the...
26
by: Michael Klatt | last post by:
I am trying to write an iterator for a std::set that allows the iterator target to be modified. Here is some relvant code: template <class Set> // Set is an instance of std::set<> class...
1
by: Christophe Poucet | last post by:
Hellom I have an issue with implicit conversions. Apparently when one calls an operator on a class Y which has a conversion operator to class X which has the operator . Sadly it will not do...
1
by: Stefan Slapeta | last post by:
Hi, I've found some strange behaviour with some smart pointers. Consider this little sample: // ********************************************************** struct MyStruct {}; template...
3
by: Chris | last post by:
I am having a very strange problem involving virtual functions in template classes. First of all, here is an extremely simplified structure of the two classes I am having problems with. ...
2
by: Paulo Matos | last post by:
Hi all, Guess I wish to do some parsing for a calculator which might include rational numbers. So I can have integers (sequence of digits possibly started by -) and rationals (two integers...
3
by: IR | last post by:
Hi, I've been trying to do the following (which doesn't compile) : template<class T, class F = Example<T struct Example { F foo(); };
7
by: yashwant pinge | last post by:
The following program is related to template... include <iostream> using namespace std; template<class T, int size = 100> class Array { T array;
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...
1
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...
0
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...
0
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,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.