473,903 Members | 5,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

constant vector

Hello,

I have been experimenting with std::vector. Say I wanted to create a vector
of integers but do not want the vector to change in size or capacity. In
otherwords, it has a fixed number of elements.

To do this I declared a vector of 4 integers as:

const vector<int> pool(4);

Now, to set values of the integers I had to use const_cast as in:

for(int i = 0; i < pool.size(); i++)
{
int *n = const_cast<int* >(&pool[i]);

*n = 50+i;
}

This will make the vector contain the numbers: 50, 51, 52, 53.

The reason for the making the vector 'const' is so that a compiler will flag
an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);

Ignoring the practicality of this trivial example, is this valid?

--
Alvin
Jul 23 '05 #1
15 4127
On Thu, 05 May 2005 18:53:07 GMT in comp.lang.c++, Alvin
<reply@in_newsg roup.ca> wrote,
const vector<int> pool(4); .... int *n = const_cast<int* >(&pool[i]); ....Ignoring the practicality of this trivial example, is this valid?


No. When you declare the vector const, the compiler is free to
implement it in such a way that modifying it after it is constructed
may not work.

Use one of the vector constructors that fully initializes it in the
form you want at the time of construction; or build a not-const vector
and create a const reference to it for public use.

Jul 23 '05 #2
Alvin wrote:
I have been experimenting with std::vector. Say I wanted to create a vector
of integers but do not want the vector to change in size or capacity. In
otherwords, it has a fixed number of elements.

To do this I declared a vector of 4 integers as:

const vector<int> pool(4);

Now, to set values of the integers I had to use const_cast as in:

for(int i = 0; i < pool.size(); i++)
{
int *n = const_cast<int* >(&pool[i]);

*n = 50+i;
}

This will make the vector contain the numbers: 50, 51, 52, 53.

The reason for the making the vector 'const' is so that a compiler will flag
an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);

Ignoring the practicality of this trivial example, is this valid?


It's probably valid. 'std::vector' allocates its contents from free store
and thus should have no particular issue with const_cast. However, if I
were to implement a vector with constant size, I'd probably wrapped the
'std::vector' in my own interface that would not have size-changing ops
available instead of declaring the vector 'const' and then tweaking it
using 'const_cast'...

V
Jul 23 '05 #3
* Alvin:

I have been experimenting with std::vector. Say I wanted to create a vector
of integers but do not want the vector to change in size or capacity. In
otherwords, it has a fixed number of elements.

To do this I declared a vector of 4 integers as:

const vector<int> pool(4);

Now, to set values of the integers I had to use const_cast as in:

for(int i = 0; i < pool.size(); i++)
{
int *n = const_cast<int* >(&pool[i]);

*n = 50+i;
}

This will make the vector contain the numbers: 50, 51, 52, 53.

The reason for the making the vector 'const' is so that a compiler will flag
an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);

Ignoring the practicality of this trivial example, is this valid?


No.

You can only (formally) cast away const for something that wasn't const
in the first place.

The simplest way to do the above is to write a function that returns a vector
which you can then use as initializer, or to use a function or functor class
instead of a vector.

More advanced, you can write an iterator class and use that to initialize the
vector.

More advanced still, you can generalize that iterator class to iterate using
any client code function or functor class to provide the values.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #4
Victor Bazarov wrote:
However, if I
were to implement a vector with constant size,


Or, if you had an implementation of TR1, you could use std::tr1::array .

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #5
or if you don't, use boost.array. It is the same as std::tr1:array,
AFAIK

Jul 23 '05 #6
Alvin wrote:
The reason for the making the vector 'const' is so that a compiler will flag an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);


Why don't you write a small wrapper over std::vector that implements
the behavior you want?

::A::

Jul 23 '05 #7
Alvin wrote:
Hello,

I have been experimenting with std::vector. Say I wanted to create a
vector of integers but do not want the vector to change in size or
capacity. In otherwords, it has a fixed number of elements.

To do this I declared a vector of 4 integers as:

const vector<int> pool(4);

Now, to set values of the integers I had to use const_cast as in:

for(int i = 0; i < pool.size(); i++)
{
int *n = const_cast<int* >(&pool[i]);

*n = 50+i;
}

This will make the vector contain the numbers: 50, 51, 52, 53.

The reason for the making the vector 'const' is so that a compiler will
flag an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);

Ignoring the practicality of this trivial example, is this valid?


Thank you everyone for your comments. Looks like the proper solution would
be to create a wrapper around std::vector that exposes only the desired
methods. But I will look into the boost::array and see what that offers.
Actually, I know very little about Boost, but it seems like a very
promising extension.

Alvin
Jul 23 '05 #8

__PPS__ wrote:
or if you don't, use boost.array. It is the same as std::tr1:array,
AFAIK


Please quote enough of the previous message to provide context for your
replies. To do so using the Google interface, click on "show options"
and use the Reply shown in the expanded header.


Brian

Jul 23 '05 #9
"Alvin" <reply@in_newsg roup.ca> wrote in message
news:nYtee.2378 6$0X6.18877@edt nps90...
I have been experimenting with std::vector. Say I wanted to create a
vector
of integers but do not want the vector to change in size or capacity. In
otherwords, it has a fixed number of elements.

To do this I declared a vector of 4 integers as:

const vector<int> pool(4);

Now, to set values of the integers I had to use const_cast as in:

for(int i = 0; i < pool.size(); i++)
{
int *n = const_cast<int* >(&pool[i]);

*n = 50+i;
} Poor choice IMO, and in theory could lead to undefined behavior
(e.g. an std::vector could implement something similar to the
small string optimization used by some std::string implementations ).
The reason for the making the vector 'const' is so that a compiler will
flag
an error if the vector is modified. For example, this will produce a
compiler error (I want this error to occur):

pool.push_back( 9);

Ignoring the practicality of this trivial example, is this valid?


Better options would be to:
a) create a function that returns the vector
b) initialize the vector from an array

Here's an example for b):
int data[4] = { 50,51,52,53 };
const vector<int> pool( data, data+4 );
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com

Jul 23 '05 #10

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

Similar topics

7
28962
by: Karen | last post by:
Hi, I have one constant variable and want to use it in two files. I put it in the header file and then include the header file. The compiler always say "error C2370: 'arraysize' : redefinition; different storage class". What shall I do? Files are listed below. I'm using Visual C++ 6.0 By the way, how to use STL (vector , for example) to create a multi-dimension array?
7
2417
by: news.hku.hk | last post by:
suppose i have a class abc, and i have an important value stored as int integer = 888; when i want to declare an array of objects: abc obj; // error said non-constant....expect constant array size....and the like What can i do if i really want 888 as the array size ???
7
2605
by: Russ Ford | last post by:
How does one define an iterator for a constant vector? ie: void printvector (vector<int>& arr) { vector<int>::iterator i; for (i=arr.begin(); i<arr.end(); ++i) cout << *i << endl; }
11
5316
by: lovecreatesbeauty | last post by:
Hello experts, Is const_cast only applied to pointers or references? If I have a constant object, then how can I remove constant attribute from it? #include <vector> #include <string> using namespace std;
8
5140
by: Al | last post by:
I'd like to declare (in a Matrix class) a two-dimentional array with user-defined coordinates. The constructor is: Matrix(int c, int l): col(c), lin(l), a(new float) {} the compiler says 'lin' should be a constant, but I want it to be defined from the user, so what should I do? and how must 'a' be declared?? help me please
6
4026
by: Amit Bhatia | last post by:
Hi, I am not sure if this belongs to this group. Anyway, my question is as follows: I have a list (STL list) whose elements are pairs of integers (STL pairs, say objects of class T). When I create a new object of class T, I would like to check if this object already exists in the list: meaning one having same integers. This can be done in linear time in a list, and probably faster if I use STL Set instead of list. I am wondering however if...
33
5585
by: desktop | last post by:
In the C++ standard sec 23.1.2 table 69 it says that erase(q) where q is a pointer to an element can be done in amortized constant time. I guess that is not worst case since std::set is practically a red-black tree where insert/delete takes O(lg n) time. Or are there some other explanation for this complexity?
8
1679
by: fabian.lim | last post by:
Hi, I have a question on constant variables. In the following code snippet, I have a function assign() that takes in an iterator to the private variable v, the number of stuff to assign (int n), and the information to assign (a const pointer to a class object Vector<TYPE>. According to the arrow below, I put a const keyword in the function. To my knowledge, this means that all private variables in this object
5
1603
by: shuisheng | last post by:
Dear All, I have a question. Assume struct A { int *p, *q; }; struct B
0
9999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9847
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
11282
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...
1
10983
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10500
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...
0
9684
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...
0
5894
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
4308
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3324
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.