Resizable Arrays

D

dms

Hi,

Is there another, more friendly way to create resizable arrays without
using the realloc function?

Thanks

David Sharp
 
P

Peter van Merkerk

Is there another, more friendly way to create resizable arrays without
using the realloc function?

Take a look at the std::vector class in the standard library. This class
is an excellent replacement for C-style arrays in most cases.
 
D

dms

Hi,

Thanks for the quick reply. Can you please give me an example of usage?

Thanks

David Sharp
 
P

Peter van Merkerk

Thanks for the quick reply. Can you please give me an example of
usage?

#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> v(3); // Create vector with 3 default constructed
elements.

v[0] = 100;
v[1] = 200;
v[2] = v[1] + v[0];

v.push_back(123); // Add one element to the v, v now has 4 elements.
v.push_back(321); // Add one element to the v, v now has 5 elements.

v.resize(10); // Resize v to 10 elements
v[9] = 12345; // Set value of last element of v

// Dump contents of v
for(int i=0; i < v.size(); ++i)
{
cout << "v[" << i << "] = " << v << endl;
}
return 0;
}


HTH
 
D

dms

That's great! Thanks.
Thanks for the quick reply. Can you please give me an example of

usage?

#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> v(3); // Create vector with 3 default constructed
elements.

v[0] = 100;
v[1] = 200;
v[2] = v[1] + v[0];

v.push_back(123); // Add one element to the v, v now has 4 elements.
v.push_back(321); // Add one element to the v, v now has 5 elements.

v.resize(10); // Resize v to 10 elements
v[9] = 12345; // Set value of last element of v

// Dump contents of v
for(int i=0; i < v.size(); ++i)
{
cout << "v[" << i << "] = " << v << endl;
}
return 0;
}


HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top