开发者

request for member `push_back' in `num', which is of non-class type `int[((unsigned int)((int)n))]'

开发者 https://www.devze.com 2023-03-27 20:50 出处:网络
#include <iostream> #include <vector> #include <numeric> using namespace std; std::vector<float> num;
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
std::vector<float> num;

float mean (float num[], float n)
{
    int i;
    float sum=0;
    for(i=0;i<n;i++)
    sum=sum+num[i];
    return (sum/n);

}
int main()  
{

    int minusElements;  
    int n;
    cout << "Enter number of Elements:";  
    cin >> n;



    minusElements = n - 1  ;
    int i,j;  
    float  temp;

    float f;
    for(i=0;i<n;i++)  
    {
    cin >> f;
    num.push_back(f);
    }


    cout << "Enter " << n << " numbers:\n";
    for(i=0;i<n;i++)  
    cin >> num[i];
    cin.get();
    float m = mean(&num[0], num.size());


    //if num is float[n] or float* (num of 开发者_高级运维elements = n)
    float mean = std::accumulate(num, num + n, 0) / n;
    cout<<mean;
}  
//46 no match for 'operator+' in 'num + n' 


push_back is generally called on a vector, not an array like int[].


You are using a regular C-style array instead of a std::vector and the compiler is complaining.

num should be declared as

std::vector<int> num;


It's pretty clear from the error message: num is not an instance of a class so you can't call methods on it. Why do you think you can call push_back on it? Where do you think push_back is defined?


num is not an std::vector, so you can't call the push_back method for it.

Maybe you intended to define num like this :

std::vector<int> num;

Note that you'd have to modify the rest of the code accordingly of course.


int i,j, num[n];

-->

int i,j;
std::vector<int> num;

Since when asking questions could be replaced by code? Say something buddy.


Decide how you want to store your numbers, in either a vector or an array, and then use the operations that are available accordingly.

It seems that you edited heavily the question, as in the opening title the compiler is complaining when you try to perform an operation of a vector in num as num in that version is an array. Then the current code has the opposite problem: num is defined as a vector and you are trying to apply an operation that is not available in vectors but rather to pointers.

The second error can be fixed by changing the call to std::accumulate to use iterators:

float mean = std::accumulate(num.begin(), num.end(), 0) / n;

NOTE: It is a really bad idea to edit the question so that existing answers no longer make sense. You are new to StackOverflow, but expect your questions to be closed if you continue with this pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消