2014-11-03 37 views
0

所以我只是試圖設置一個給定的數組索引值計數函數的結果。我已經閱讀了有關計數函數的API,但在嘗試將我的參數傳遞給所述計數函數時,我一直收到expression must have class type錯誤。功能找到一個數組的開始和結束

這是到目前爲止我的代碼:

#include <iostream> 
#include <limits> 
#include <algorithm> 
#include <array> 

using namespace std; 

int main(){ 

    const size_t ARRAY_SIZE = 400; 
    int totalElements; 
    cout << "How many grades will you be entering?: "; 
    cin >> totalElements; 

    int gradesArray[ARRAY_SIZE]; 
    for(int i = 0; i < totalElements; i++){ 
     cout << "Please enter a grade: "; 
     cin >> gradesArray[i]; 
    } 
    //to be incrimented with each count of a certain grade, from 0-5 
    int countOfGrades[6] = {0, 0, 0, 0, 0, 0}; 

    countOfGrades[0] = count(gradesArray.begin(),gradesArray.end(),0); 

    return 0; 

}//end of main 
+0

你在哪裏定義了'count'? – 2014-11-03 00:46:02

+0

http://www.cplusplus.com/reference/algorithm/count/ – FluffyKittens 2014-11-03 00:46:38

+0

@ScottHunter:他沒有:http://en.cppreference.com/w/cpp/algorithm/count – 2014-11-03 00:46:38

回答

3

數組沒有載體和他們沒有一個begin()end()函數(或任何成員函數,它們不是類的類型!)

但是,您可以使用std::beginstd::end或只是通過陣列和最後一個元素的地址+ 1.

+0

爲了澄清,這將看起來像'std :: count(std :: begin(gradesArray),std :: end(gradesArray),0)' – 2014-11-03 00:55:20

+0

謝謝,我習慣於Ruby,其中一切都是類類型。 – FluffyKittens 2014-11-03 00:55:35

2

數組沒有開始和結束的方法,也許你想std::vector。或者只傳遞指針,它遵循count所需的迭代器接口。

count(gradesArray, gradesArray + ARRAY_SIZE, 0); 
+0

API清楚地表明他們已經將begin()和end()作爲成員函數?我錯過了什麼? http://www.cplusplus.com/reference/array/array/begin/ – FluffyKittens 2014-11-03 00:50:53

+0

這是爲'std :: array'類型,它是不同於常規數組。 – msandiford 2014-11-03 00:52:49

+0

哦,我明白了。這很有道理,即使它看起來不太直觀。感謝您的幫助。 – FluffyKittens 2014-11-03 00:54:14

0

std::beginstd::end非成員函數可以採用容器或數組。 container.begin()container.end()成員功能。常規數組沒有任何成員函數。既然你有一個支持C++ 11的編譯器,沒有理由使用原始數組。首選std::arraystd::vector

std::array<int, ARRAY_SIZE> gradesArray; 
相關問題