How Does the capacity changes as the size increases? Well, this simple test code and chart will clear up the questions.
// This program demonstrates the vector size member function.
#include <iostream>
#include <vector>
#include<cmath>
#include<fstream>
using namespace std;
int main() {
ofstream outFile;
outFile.open("c:\\temp\\analysis.csv");
vector<int> values;
cout << typeid(values).name() << endl;
outFile << "size, capacity, diff, count" << endl;
// Put a series of numbers in the vector.
for (int count = 0; count < 20; count++) {
values.push_back(count * 2);
outFile << values.size() << "," << values.capacity() << ","
<< abs((int)(values.size() - values.capacity()))
<< "," << count << endl;
}
vector<int> temp;
for (int i : values) //even copying based on size value will increment capacity beyond size
temp.push_back(i);
values.shrink_to_fit(); //size will match capacity
outFile.close();
return 0;
}
This same kind of effect can be observed with string as well.
// This program demonstrates the vector size member function.
#include <iostream>
#include <vector>
#include<cmath>
#include<fstream>
#include<string>
using namespace std;
int main() {
ofstream out("c:\\temp\\out.csv");
string item = "a";
out << "count,size,capacity" << endl;
cout <<"1,"<<item.size() << "," << item.capacity() << "," << endl;
for (int i = 2; i < 1000; i++) {
item += "a";
out <<i<<"," << item.size() << "," << item.capacity() << "," << endl;
}
out.close();
return 0;
}
No comments:
Post a Comment