在向量中查找一组整数 [英] Finding a group of integers in a vector

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

问题描述

在我的任务中,我应该找到向量中是否存在40-50之间的数字,如果它存在的是它们的索引。



没有解决方案我每次尝试零作为cnt的值时都会尝试工作,我最近开始使用向量,我认为这里的问题是我将它们视为数组



我尝试过:



 void Findthem(vector< cam>& W){
int cnt = 0;
vector< int> r = {40,41,42,43,44,45,46,47,48,49,50}; //想要年龄
for(int i = 0; i< W.size(); i ++)
{
for(int j = 0; j< 11; j ++)
{
if(W [i] .age!= r [j])
{
cnt ++;

}
}
}







 void Findthem(vector< cam>& W){
int cnt = 0;
for(int i = 0; i< W.size(); i ++)
{
if(W [i] .age> 40&& W [i]。年龄<50)
{
cnt ++;

}

}

解决方案

在这两种情况下,您都在计算事件的数量但是当函数返回时,计数丢失。更改函数,使其返回计数值。


该任务是一个简单的homwework。你需要从40循环到50并找到索引。

 vector< int>水库; 
for(int j = 40; j< 50; j ++)
{
res.push_back(-1); //找不到
for(int i = 0; i< ; W.size(); i ++)
{
if(W [i] .age == j])//找到
{
res [j-40] = i; //设置索引作为结果
break;
}
}
}

学会使用调试器


In my task I should find if there exists numbers between 40-50 in a vector and if it exists what's the index of them.

None of the solutions that I've tried works each time I get zero as the value of cnt, I've recently started to work with vectors and I think the issue here is that I'm treating them like arrays

What I have tried:

void Findthem( vector<cam> & W){
    int cnt = 0;
    vector <int> r = {40,41,42,43,44,45,46,47,48,49,50};  //wanted ages
    for (int i=0; i<W.size(); i++)
    {
        for (int j=0; j<11; j++)
        {
            if ( W[i].age != r[j] )
            {
                cnt++;
                
            }
        }
    }




void Findthem( vector<cam> & W){
    int cnt = 0;
    for (int i=0; i<W.size(); i++)
    {
            if ( W[i].age > 40 && W[i].age < 50 )
            {
                cnt++;
                
            }
        
    }

解决方案

In both cases you are counting the occurrences but when the function returns that count is lost. Change the function so it returns the count value.


That task is a simple homwework. You need to loop from 40 to 50 and find the index.

vector <int> res;
for (int j=40; j<50; j++) 
{
  res.push_back(-1);//not found
        for (int i=0; i<W.size(); i++)
        {
            if ( W[i].age == j] )//found
            {               
               res[j-40] = i;//set index as result
               break;
            }
        }
    }

Learn to use the debugger.


这篇关于在向量中查找一组整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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