+ 2
Help! Final assignment
We have to make a vector by an initialization list and then we have to give the length of the vector using the sizeof() function. How exactly do we write a sizeof() function? (We are using c++, this is a beginner course)
2 odpowiedzi
+ 2
The sizeof is not a function but an operator in C++
Do you wish to rewrite the sizeof operator definition or just use it to get the size/ length of the vector?
If all you want is to retrieve the length , you should use size() to get the size of the vector, rather than using sizeof like we do for normal arrays.
This is as sizeof(vec)/sizeof(vec[0]) does not work as expected with vectors...
Consider the following program:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vec = {1,2,3,4};
// Initialized a vector using list
cout<<sizeof(vec)/sizeof(vec[0])<<endl;
cout<<vec.size()<<endl; // Returns true length.
for(int i:vec) cout<<i<<" ";
}
In this program, even when you change the elements during initialization, the sizeof(vec) returns a constant value - 12, which is less than the size we expected for 4, 5 or more elements. So use the size method instead...
+ 1
Okay I just had to delete my question that I asked you... because it was written already. Thank you so much for your help