I'm in the process of writing a program for selection sort. I just posted something regarding std::vector, however this post is on a different subject.
I was able to compile the program, however it was running into run-time error when insert() was invoked in the main method.
My ArrayS has the code below as a copy constructor and also to initialize nElems to 0 when ArrayS is created.
[ArrayS.cpp]
ArrayS::ArrayS(int max)
{
std::vector<long> a;
nElems = 0;
}
void ArrayS::insert(long value) // put element into array
{
a[nElems] = value; // insert it
nElems++; // increment size
}
[ArrayS.h]
private:
std::vector<long> a;
int nElems;
Now, do I need get/set method in the ArrayS.cpp to manipulate nElems? I'm not sure how in C++ you work with private variables.
Thank you.
Vectors keep track of their size. And to be efficient, a[nElems]
will assume that your vector
is large enough to accommodate that access.
It looks like you want:
void ArrayS::insert(long value) // put element into array
{
a.push_back(value); // insert it AND increment size
}
It also looks like you can disregard nElems
. If you want the vector's size, just call a.size()
.