Topic: Why this behavior?
Author: seitz@ix.netcom.com (Matt Seitz)
Date: 1997/09/19 Raw View
In article <Pine.PMDF.3.95.970913102712.587315117A-100000@WCUVAX1.WCU.EDU>, Carl Mummert <cm11214@WCUVAX1.WCU.EDU> wrote:
>I am curious about a behavior fo the vector class.
>
>What is the reasoning behind this not working:
>
>vector<int> vec(3);
>vec[5] = 2; //not correct; operator[] won't
> //allocate space
According to Stroustrup. the reason was efficiency (C++ PROGRAMMING LANGUAGE,
3rd Ed., section 16.3.3). In order for vec[n] to automatically allocate
space, it would need to compare n to the current vector size every time vec[n]
is used. In order to better match the speed of C arrays, it was decided that
vectors would not do range checking when the subscript operator was used.
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]
Author: Carl Mummert <cm11214@WCUVAX1.WCU.EDU>
Date: 1997/09/14 Raw View
I am curious about a behavior fo the vector class.
What is the reasoning behind this not working:
vector<int> vec(3);
vec[5] = 2; //not correct; operator[] won't
//allocate space
The idea of vectors, after all, is that they be
self-defining and that they would automatically
allocate memory as needed.
But the standard (fairly clearly) indicates that
operator[] is only for access to the vector, and
that you must find other ways to insert new
objects past the end of the vector.
And yes, I do know I could use a map. I don't
want to. I just want to understand the reasoning
behind this behavior.
Thanks
Carl
--------------- cm11214@wcu.edu ---
One must imagine Sysiphus happy.
---
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]