簡體   English   中英

我不明白為什么for循環在此代碼上不起作用

[英]I can't figure out why for-loop doesn't work on this code

我想使vector(mycount)指示myvec中元素的頻率。 你能讓我知道怎么了嗎?

#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;
}

我懷疑您打算使用:

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;
}

您的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM