向量计数函数C ++ [英] vector count function C++

查看:132
本文介绍了向量计数函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量

  vector< int& vec; 

它存储了随机数{5,7,8,9,13,15,17} p>

并且我有一个向量,如果它们是素数,则将前一个向量的数字计算为1或0。

  vector< int> vec_prime_number; 

所以对于前一个,它将是{1,1,0,0,1,0,1 }



我试图使用count函数只保存素数。我会遇到一些问题。



理想情况下,我想让vec有
{5,7,13,17 } //换句话说,它只有素数



我尝试过像

这样的东西。

  int cnt = count(vec.begin(),vec.end(),vec_prime_number())

但我不能得到任何它的工作。

解决方案

std的文档: :count 说:


返回范围[first,last] val。


,因此您应该使用以下内容,以获取素数的数字:

  int cnt = count(vec_prime_number.begin(),vec_prime_number.end(),1); 

你可以看到


I have a vector

vector<int> vec;

it's storing random numbers {5, 7, 8, 9, 13, 15, 17}

and I have a vector that is evaluating the previous vector's numbers as 1 or 0 if they are a prime number or not

vector< int> vec_prime_number;

so for the previous it would be {1, 1, 0, 0, 1, 0, 1}

I'm trying to use the count function to save only the prime numbers in it. And I'm having some problems with doing it.

Ideally, I would like to make it so that vec has {5, 7, 13, 17} //in other words, only prime numbers in it

I've tried stuff like

int cnt = count(vec.begin(), vec.end(), vec_prime_number())

but I can't get any of it to work. Any ideas on how to get count to store only the prime numbers?

解决方案

The documentation of std::count says:

Returns the number of elements in the range [first,last) that compare equal to val.

so you should use something along the lines of the following, to get the number of prime numbers:

int cnt = count(vec_prime_number.begin(), vec_prime_number.end(), 1);

as you can see.

这篇关于向量计数函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆