this is a folow up to this https://softwareengineering.stackexchange.com/questions/256241/c-coding-practice-class-vs-free-functions question I posted a few day ago. In short, the idea is to create a custom vector class for statistical data analysis.
I got a great response, that made me realise that I need to understand: why use size_t in a constructor of a container class and why use it anyway?
Here is a part of the proposed solution:
template<class T>
class vect
{
std::vector<T> m;
public:
vect(size_t n) :m(n) {}
void addTo(T a){ m.push_back(a); }
std::vector<T> get() const { return m;}
... more functions and overloaded operators
};
I understand that size_t is an (unsigned int) data type and should be used to indicate that it's value should represent the size of n object.
In order to understand the behaviour of size_t I did the following:
int main() {
vect<int> m(0);
vect<int> n(100);
std::cout << sizeof(n) << std::endl;
std::cout << sizeof(m) << std::endl;
std::cout << sizeof(m.get()) << std::endl;
for (int i = 0 ; i < 100; i++) {
m.addTo(i);
}
std::cout << sizeof(m) << std::endl;
std::cout << sizeof(m.get()) << std::endl;
}
all of which return "24". (I expected a change in the size of the object after adding parameters to it.) However:
for(int i = 0; i<100;i++)
std::cout << m[i] << std::endl;
nicely prints out all values from 0 to 100. Thus I know that there are 100 integers stared in the vector, but then why is its size 24 and not 100?
Obviously I am new to c++ programming and to make things worse this is my first template class.
Thank you for your time and patience, I really appreciate it.