c++ - 我不明白为什么 for-loop 不适用于此代码

标签 c++ for-loop vector

我想制作表示 myvec 中元素频率的 vector (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;
}

最佳答案

我怀疑你打算使用:

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

关于c++ - 我不明白为什么 for-loop 不适用于此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176149/

相关文章:

c++ - 如何在 C++ 中获得一个月的第三个星期五?

C++使用STL列表,如何将现有列表复制到新列表中

python - 为什么我的代码只写最后一个变量?

python - Python 中的特定范围后不出现值

c++ - 将局部 vector 复制到 map 中某个键的值时遇到段错误

c++ - 基于对象指针在 vector 中获取对象

c++ - 在 main() c++ 中输入二维 vector

c++ - 如何将控制台 (stdout) 添加为 g3log 中的接收器?

c++ - 矩阵求逆和转置 R vs c++

javascript - 以设定的时间增量循环对象