c++ - c ++将向量中出现n次的所有元素作为向量返回
问题描述
目标:返回 vector 中出现 N 次的所有元素,A
并将结果放入 vector 中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 <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator> // std::back_inserter
#include <algorithm> // std::copy
#include <set>
#include <map>
using namespace std;
int main()
{
std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
std::vector<int> shows;
std::map<int, int> freqOfv;
for(const auto& i: v)
{
freqOfv[i]++;
}
std::set<int> s(v.begin(), v.end());
int N = 2; //Can be read from stdin as well...
for ( auto it = s.begin(); it != s.end(); it++ )
{
if(freqOfv[*it] ==N)
{
shows.push_back(*it);
}
}
for (std::vector<int>::const_iterator i = shows.begin(); i != shows.end(); ++i)
{
std::cout << *i << ' ';
}
return 0;
}
解决方案
正如评论中所建议的,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;
}
}
这会产生以下输出:
The value 3 occurs 2 times.
The value 4 occurs 2 times.
当然,您#include <map>
一开始需要在代码中使用地图。
推荐阅读
- awk - awk 命令 - 定义单词的大小
- gitpython - 使用 GitPython 下载特定版本
- c# - 带有 Swagger 的通用 ApiController 基类
- android - 为什么 popBackStack 不使用 FragmentStatePagerAdapter 恢复到上一个片段?
- php - 无法制作 JSON 多级 PHP
- gcc - 与系统库动态或静态链接的库的交叉编译
- r - 拆分单元格的内容并创建一个新列表
- python - 如何在字符串的二进制表示中将 'b' 替换为 0 或 1
- java - 如何从地址位置获取直接字节缓冲区
- html - 为什么这个 HTML 有效