Re: std::vector: reserve required?
Mike -- Email Ignored wrote:
On Fri, 04 Jul 2008 08:30:37 -0700, acehreli wrote:
On Jul 4, 7:54 am, callumurquh...@googlemail.com wrote:
http://www.cplusplus.com/reference/stl/vector/operator[].html
If the OP did not concentrate on the vec.reserve(en), the document you
show could be used to help with the problem. But because the OP does
expect some behavior from vec.reserve(en), the problem is not with
operator[].
Ali
Another test using:
vec.reserve(en);
for (int jj = 0; jj < en; ++jj)
vec[jj] = jj;
cout << "vec.size() = " << vec.size() << endl;
prevents the crash, but vec.size() returns zero,
What does vec.capacity() return?
showing that
in this case, reserve() really does not work.
I think it doesn't do what you expect. But why do you think it doesn't work?
Please consider this:
#include <iostream>
#include <vector>
int main() {
const unsigned int en = 10;
std::vector<int> v;
//
std::cout << "a " << v.size() << " " << v.capacity() << std::endl;
v.reserve(en);
std::cout << "b " << v.size() << " " << v.capacity() << std::endl;
//
for(unsigned int i=0; i<en; i++) {
v[i] = i;
}
//
v.push_back(-8);
std::cout << "c " << v.size() << " " << v.capacity() << std::endl;
//
for(unsigned int i=0; i<en; i++) {
std::cout << "[" << i << "] " << v[i] << std::endl;
}
}
Also, please consider this:
#include <iostream>
#include <vector>
int main() {
const unsigned int en = 10;
std::vector<int> v;
std::cout << "a " << v.size() << " " << v.capacity() << std::endl;
v.resize(en); // there's more than one way to do it
std::cout << "b " << v.size() << " " << v.capacity() << std::endl;
//
v[0] = -8;
v[9] = -7;
v.push_back(-9);
std::cout << "c " << v.size() << " " << v.capacity() << std::endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout,
" "));
}
LR