vector::reserve increment vector capacity,not size.
capacity and size are diff.
MSDN sample.
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Add one element to the end of the vector, an int with the value 42.
theVector.push_back(42) ;
// Show statistics about vector.
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << endl;
// Ensure there's room for at least 1000 elements.
theVector.reserve(1000);
cout << endl << "After reserving storage for 1000 elements:" << endl;
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << endl;
// Ensure there's room for at least 2000 elements.
theVector.resize(2000);
cout << endl << "After resizing storage to 2000 elements:" << endl;
cout << "theVector's size is: " << theVector.size() << endl;
cout << "theVector's maximum size is: " << theVector.max_size()
<< endl;
cout << "theVector's capacity is: " << theVector.capacity() << endl;
}
Program Output is:
theVector's size is: 1
theVector's maximum size is: 1073741823
theVector's capacity is: 1
After reserving storage for 1000 elements:
theVector's size is: 1
theVector's maximum size is: 1073741823
theVector's capacity is: 1000
After resizing storage to 2000 elements:
theVector's size is: 2000
theVector's maximum size is: 1073741823
theVector's capacity is: 2000
HI, when I try the following code, I get a segfault when compiled with
VC.NET and g++ under cygwin.
#1 vector<int> vi;
#2 vector<int>::iterator ii = vi.begin();
#3 vi.reserve(10);
#4 for(int i = 0; i < 10; ++i) {
#5 *ii++ = 4;
#6 }
#7 copy(vi.begin(), vi.end(), ostream_iterator<int>(cout, " "));
Here is my break down on why this code should work (fill a vector with
numbers, nevermind v[i] syntax, or v.push_back(), or the fill(...) stl
function. I really wanted to know why the use of iterators causes a
problem here).
#1 - v.size is 0;
#2 - initiate a interator and point to v.begin().
#3 - make space for 10 more elements, v.size() is still 0;
#4-6 - loop and assign each space in the vector a number. #5 is where
segv happens.
I was under the assumption that reserve will make space available to add
more element, which the iterator will be able to walk through them. I'd
appreciate any help on this issue.
Smith
---
Posted via
news://freenews.netfront.net
Complaints to
ne**@netfront.net