我无法弄清楚为什么for循环不适用于此代码

时间:2015-10-16 17:21:51

标签: c++ for-loop vector

我想制作指示myvec中元素频率的向量(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(); });

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

    return 0;
}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}