A
Alvin
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);
*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?
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);
*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?