简体   繁体   中英

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

I want to make the vector( mycount) that indicates frequency of the elements in myvec. Can you please let me know what is wrong?

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

I suspect you meant to use:

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

your mycount definition is wrong. Check the below code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM