[英]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. 我想使vector(mycount)指示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. 您的mycount定义错误。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.