C++ c++;作为向量返回向量中出现n次的所有元素

C++ c++;作为向量返回向量中出现n次的所有元素,c++,vector,element,counting,find-occurrences,C++,Vector,Element,Counting,Find Occurrences,目标:返回向量A中出现N次的所有元素,并将结果放入向量B 预期结果: --Begin With--- Vector A=(10,20,30,30,40,50,100,50,20,100,10,10,200,300) Do some code to return the name of elements that appear in Vector A when N=3 Result should be Vector B=(10) //because only 10 is in vector

目标:返回向量
A
中出现N次的所有元素,并将结果放入向量
B

预期结果:

--Begin With---

Vector A=(10,20,30,30,40,50,100,50,20,100,10,10,200,300)

Do some code to return the name of elements that appear in Vector A
when N=3

Result should be Vector B=(10) //because only 10 is in vector A N=3 times.
我的尝试: 我得到了放置在另一个向量中的所有元素的计数,但我没有能够返回所有出现次数
N
的元素的部分如果这意味着速度提高,我会灵活处理

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>     // std::back_inserter
#include <algorithm>    // std::copy

int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };

    std::vector<std::pair<int, int> > shows;
    int target1;
    int num_items1;
    int size = static_cast<int>(v.size());

    for(int x=0; x<size; x++)
    {
        target1 = v[x];

        num_items1 = std::count(v.begin(), v.end(), target1);

        shows.push_back(std::make_pair(target1, num_items1));

        std::cout << "number: " << target1 << " count: " << num_items1 << '\n';
    } 
}
#包括
#包括
#包括
#包括
#include//std::back\u插入器
#包括//标准::复制
int main()
{
向量v{1,2,3,4,4,3,7,8,9,10};
std::矢量显示;
INTTARGET1;
int num_items1;
int size=static_cast(v.size());

对于注释中建议的(int x=0;x,
std::map
将简化代码:

int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };    
    std::map<int, int> freqOfv; 
    for(const auto& i: v)
        freqOfv[i]++;

    int N = 2; //Can be read from stdin as well...

    for(const auto& i: freqOfv)
    {
        if(N == i.second)
            std::cout << "The value " << i.first << " occurs " << N << " times." << std::endl;
    }   
}

当然,要在代码中使用映射,您需要在开始时包含

您可以在这里找到
std::map freq;
用于跟踪计数。每次找到元素时,
freq[v[x]]++
投票决定关闭,因为太宽。堆栈溢出不是让人为您编写代码的地方。尝试编写代码来存储/返回类型,如果您有问题,发布有问题的代码,并说明问题所在。现在尝试代码…是否有任何方法将所有值转储到数组/向量/映射或wha中一次完成所有操作而不必循环成什么东西?我必须完成1000次循环,通过循环存储返回值的速度比我使用python numpy bincount(一次将所有结果返回到数组)慢得多。有什么想法吗?谢谢。你的意思是想避免第二次
for
循环?@p-w谢谢,是的,我要避免(const auto&i:frequeofv){if(N==i.second)std::cout从向量中的循环,请创建一个包含向量唯一元素的集合。然后在for循环中(您在问题中发布的代码),使用集合元素进行迭代,如果计数等于N,则将该对添加到
shows
vector中。@p-w我感谢您的帮助!我将编辑原始问题以包含答案。
int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };    
    std::map<int, int> freqOfv; 
    for(const auto& i: v)
        freqOfv[i]++;

    int N = 2; //Can be read from stdin as well...

    for(const auto& i: freqOfv)
    {
        if(N == i.second)
            std::cout << "The value " << i.first << " occurs " << N << " times." << std::endl;
    }   
}
The value 3 occurs 2 times.
The value 4 occurs 2 times.