2015-10-16 66 views
0

我想使矢量(mycount)指示myvec中元素的頻率。你能讓我知道什麼是錯的嗎?我不明白爲什麼for循環無法在此代碼上工作

#include <iostream> 
#include <vector> 
#include <cstdlib> 
#include <functional> 
#include <algorithm> 
using namespace std; 

int main() { 
    int num; 

    cout << "How many numbers do you want to read in?" << endl; 
    cin >> num; 


    vector<int> myvec(num); 

    std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); }); 

    for (int i = 0; i < num; ++i) { 
    vector<int> mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]); 
     cout << mycount[i] << endl; 
    } 

    return 0; 
} 
+0

你至少應該解釋一下什麼是錯的。 – skypjack

+0

你能告訴我們這有什麼問題嗎?你有錯誤嗎?垃圾值? – NathanOliver

+0

我收到錯誤。比如「表達式不計算爲常量」 – Ezerk

回答

1

我懷疑你的意思是使用:

vector<int> myvec(num); 

// Create a vector for storing the counts as well. 
vector<int> mycount(num); 

std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); }); 

for (int i = 0; i < num; ++i) { 

    // Get the counts of the element at this index and store it. 
    mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]); 

    cout << mycount[i] << endl; 
} 
+0

謝謝,這就是我的意思。但仍然無法理解我的循環代碼有什麼問題? – Ezerk

+0

@Ezerk,你問爲什麼'std :: vector mycount [i] = ...'不工作? –

+0

是的,那是我的問題。 – Ezerk

0

你的mycount定義是錯誤的。檢查下面的代碼

#include <iostream> 
#include <vector> 
#include <cstdlib> 
#include <functional> 
#include <algorithm> 
using namespace std; 

int main() { 
    int num; 

    cout << "How many numbers do you want to read in?" << endl; 
    cin >> num; 


    vector<int> myvec(num); 

    std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); }); 

    vector<int> mycount(num); \\declare mycount with num elements 

    for (int i = 0; i < num; ++i) { 
    \\populate the counter for each element 
    mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]); 
     cout << mycount[i] << endl; 
    } 

    return 0; 
} 
+0

謝謝,但爲什麼mycount在我的代碼中的定義是錯誤的?我想知道爲什麼我不能像我的代碼那樣在for循環中編寫向量定義的原因。 – Ezerk

+0

語法錯誤。但你可以在裏面移動定義。該代碼將工作。但是在每次循環迭代中,矢量將被創建並銷燬(編譯器優化可以避免它)。在這種情況下,最好使用一個簡單的整數'int tmp_count = count(myvec.begin(),myvec.end(),myvec [i]);' – knightrider

相關問題