Re: string's size and capacity question
"wxghust" <wxghust@gmail.com> wrote in message
news:1190009898.417180.261050@r29g2000hsg.googlegroups.com...
On 9??17??, ????1??19??, "pas...@gmail.com" <pas...@gmail.com> wrote:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string empty;
string small = "bit";
string larger = "Elephants are a girl's best firend";
cout << "Size:\n";
cout << "\tempty: " << empty.size() << endl;
cout << "\tsmall: " << small.size() << endl;
cout << "\tlarger: " << larger.size() << endl;
cout << "Capactites:\n";
cout << "\tempty: " << empty.capacity() << endl;
cout << "\tsmall: " << small.capacity() << endl;
cout << "\tlarger: " << larger.capacity() << endl;
empty.reserve(50);
cout << "Capacity after emtpy.reserve(50): ";
cout << empty.capacity() << endl;
return 0;
}
I get result:
Size:
empty: 0
small: 3
larger: 34
Capactites:
empty: 0
small: 3
larger: 34
Capacity after emtpy.reserve(50): 50
It is different from ??C++ Primer plus 5th??16.4str2.cpp.
yes, i ran this program in DEV C++, and get the same result,
i change string to vecter, get the same result too.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
std::vector<char> empty;
std::vector<char> small;
std::string foo = "bit";
small.assign(foo.begin(), foo.end());
std::string foo2 = "Elephants are a girl's best firend";
std::vector<char> larger(foo2.begin(), foo2.end());
cout << "Size:\n";
cout << "\tempty: " << empty.size() << endl;
cout << "\tsmall: " << small.size() << endl;
cout << "\tlarger: " << larger.size() << endl;
cout << "Capactites:\n";
cout << "\tempty: " << empty.capacity() << endl;
cout << "\tsmall: " << small.capacity() << endl;
cout << "\tlarger: " << larger.capacity() << endl;
empty.reserve(50);
cout << "Capacity after emtpy.reserve(50): ";
cout << empty.capacity() << endl;
system("PAUSE");
return 1;
}
i think maybe there are some problems in primer.
=============
The primer is showing the results from his system. System being OS and
compiler. Each compiler can do it different as long as they follow the
standard. Getting extra memory is okay, as long as it gets at least what
you requested, which yours did.