2

So right now I have a class, called Set, in C++. In it, I have an integer called mCardinality, and an integer array called mElements. I want to be able to accept an integer in the constructor for mCardinality, then use this to assign a size to my integer array, is there any way to do this, or do I absolutely have to have a size for it right off the bat? (I guess I could just make the size the maximum integer, then only use the cardinality for limiting the loops where I deal with the elements, but a neater solution would be preferable).

I did see on here that there may be a way to use std::vector to resize an array, will that work? And...how would that code look? And do vectors work just like arrays in C++ for everything else I want to do with it?

4 Answers 4

3

Your options are these:

  1. use std::vector or
  2. use plain old array

With vector (recommended):

class YourSet { public: YourSet(int size) : elements(size) { } private: std::vector<int> elements; }; 

With array (not really recommended because of possible exception safety issues):

class YourSet { public: YourSet(int size) { elements = new int[size]; } ~YourSet() { delete[] elements; } private: int* elements; // no implementation to prevent shallow copying YourSet( const YourSet&); void operator=(const YourSet&); }; 
Sign up to request clarification or add additional context in comments.

2 Comments

I would prefer to use just the array. How would I do that?
@Taylor Matyasz: I included that, but really vector is better.
1

std::vector will work for your purposes.

#include <vector> class Set { Set(int len) : mElements(len) { } void do_smth() { size_t vector_len = mElements.size(); int index = 0; int element = mElements[index]; } std::vector<int> mElements; }; 

Comments

1

Vector holds pointer, and when it`s needed reallocate memory.

T* new_ptr = new T[new_size]; std::copy(ptr, ptr + size, new_ptr); delete[] ptr; ptr = new_ptr; size = new_size; 

It is simple example. Vector uses allocator, but at fact something like this.

Comments

1

GO for a vector. It will resize itself automatically when you add or remove items from it, and you can specify the size of it also if needed.

 vector<myClass> m_vClasses; myClass myNewObject; m_Classes.push_back(myNewObject); // Vector resized when you add new element 

You won't need to worry about memory or other issues (unless myClass is a pointer that points to dynamically allocated memory) assuming that your myClass destructor correctly frees any memory that the class allocates. The vector will deal with the resizing for you automatically.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.