I am learning how to work with std::vector and want to access its values and functions. I have a vector object inside another object called spectrum. Now when I try to determine the capacity of the vector using .capacity it works fine if I just declare the vector. But when I declare the vector inside another object, I get syntax errors.
The error:
test.c++:36: error: base operand of ‘->’ has non-pointer type ‘Spectrum’
As mentioned already below, -> should be a dot.
What I want is to determine the capacity of the container, and even though it now compiles it gives result 0 instead of the 8 I would expect.
The code:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/* spectrum */
class Spectrum{
public:
float oct;
vector<float> band;
float total(){
int k;
float lpow;
// logarithmic summation
for(k = 0; k < oct; k++){
lpow = lpow + pow(10, band[k]);
}
return(10*log10(lpow));
}
Spectrum(int max_oct = 3){
oct = max_oct;
cout << "max oct = " << max_oct << endl;
vector<float> band(max_oct); //create vector/array with max_oct bands
cout << (int)band.capacity() << endl;
}
};
int main()
{
//does not work in a class
Spectrum input(8);
cout << (int)input->band.capacity() << endl;
//does work outside of a class
vector<float> band(8);
cout << (int)band.capacity() << endl;
}
The line
vector<float> band(max_oct);doesn’t do what you think it does.It defines an automatic variable called
bandin the scope of the Spectrum constructor. It doesn’t touch the member variable also calledband: in fact it “hides” it, so that any later references tobandin the constructor refer to the automatic variable, not the member variable (which you could access withthis->band).What you want is:
or (less good, because it constructs an empty vector and then resizes it, rather than constructing it the right size in the first place):
By the way, I think you might be confusing the
sizeand thecapacityof vectors (not sure though from what you say). The single-arg constructor ofvectorcreates a vector with the specified size. So if you don’t already, you should expect the capacity to be 8 or more, rather than 8.[Edit: in answer to your next question, you need to initialize
lpowintotal():float lpow = 0;]