473,406 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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 4083
On Thu, 05 May 2005 18:53:07 GMT in comp.lang.c++, Alvin
<reply@in_newsgroup.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_newsgroup.ca> wrote in message
news:nYtee.23786$0X6.18877@edtnps90...
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
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
--


boost::array<int, 4> pool = {50,51,52,53};

??

Jul 23 '05 #11
"__PPS__" <bl******@mail.ru> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
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 );


boost::array<int, 4> pool = {50,51,52,53};


Sure, but this is pretty much the equivalent of
the first code line above.
It doesn't replace the second line if it is a
vector<int> that is then actually required.

Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 23 '05 #12

Ivan Vecerina wrote:
"__PPS__" <bl******@mail.ru> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
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 );


boost::array<int, 4> pool = {50,51,52,53};


Sure, but this is pretty much the equivalent of
the first code line above.
It doesn't replace the second line if it is a
vector<int> that is then actually required.

Yes it looks like the first line of code; Yes it doesn't replace the
second line - you just don't need it anymore. It creates a constant
size array of 4 integers.

Jul 23 '05 #13
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?

const vector creates indeed a const vector (it can;t be modified). If you want to remove
its constness you can do:
#include <vector>

int main()
{
using namespace std;

const vector<int> pool(4);

//...

vector<int> *pvec= const_cast<vector<int> *>(&pool);
for(vector<int>::size_type i = 0; i < pool.size(); ++i)
(*pvec)[i] = 50+i;
}

However this is tricky, and I think it is undefined behaviour for an object originally
declared as const (I think it is about to be used for originally non-const objects, from
inside a function with const arguments for example).


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #14
all this casting constness away is a bad decision - probably the
original author should reconsider if it must be const vector (or better
boost::array) at all.
don't do things like this, you cannot write/modify into const obects by
casting away constness - it leads to undefined behavior. As someone
already noted, compilers are free to optimize const objects in some
way, so that it could be impossible to modify objects...
http://www.google.ca/search?hl=en&q=...e+Search&meta=

"..Depending on the type of the referenced object, a write operation
through the resulting pointer, reference, or pointer to data member
might produce undefined behavior."

Jul 23 '05 #15
"__PPS__" <bl******@mail.ru> wrote in message
news:11*********************@f14g2000cwb.googlegro ups.com...

Ivan Vecerina wrote:
"__PPS__" <bl******@mail.ru> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
>
>> 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 );
>
> boost::array<int, 4> pool = {50,51,52,53};


Sure, but this is pretty much the equivalent of
the first code line above.
It doesn't replace the second line if it is a
vector<int> that is then actually required.


Yes it looks like the first line of code; Yes it doesn't replace the
second line - you just don't need it anymore. It creates a constant
size array of 4 integers.

Same for: int data[4];

I am fully aware of the advantages of boost::array
over C-style array, but I do not think that they
are relevant in the context of the OP question.
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 23 '05 #16

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

Similar topics

7
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;...
7
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...
7
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
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>...
8
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'...
6
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...
33
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...
8
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),...
5
by: shuisheng | last post by:
Dear All, I have a question. Assume struct A { int *p, *q; }; struct B
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
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
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,...
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...
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...

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.