打印总数和大于数字的元素的索引

时间:2018-11-17 19:10:22

标签: c++ arrays algorithm indexing

我想找到大于100的数组元素的总数索引

例如: 第一行是房屋数量。第一列是房屋的正方形,第二列是房屋的价格。我想打印出价格大于100的房屋。

6

42 15 

110 20

125 160 

166 180

42 10

110 39  

输出应如下所示:

2 (total number of the houses)  3 (index of the first house) 4 (index of the second house) 

我的代码:

#include <iostream>
using namespace std;

int main()
{
   int house, square[100], price[100], counter=0;
   cin >> house;

   if ( price[i] > 100)
    counter++;
 }
    cout << counter << endl;
    return 0;
}

我不知道如何获得索引,有人可以帮忙吗?

4 个答案:

答案 0 :(得分:1)

首先,您的代码出现编译错误,额外的}

第二,要获取索引,只需获取一个变量i,然后在每次循环后将其递增。

#include <iostream>
using namespace std;

int main()
{
   int house, greter_prices[100], counter=0;
   cin >> house;

   int i = 0;
   int price_index=0;
   while(i< house){
    int size;
    cin >> size;
    int price;
    cin >> price;
    if ( price > 100){
      counter++;
      greter_prices[price_index++]=i;
    }
    i++;
   }

   cout << counter<<" ";
   i=0;
   while(i<price_index){
    cout << greter_prices[i]<<" ";  
    i++;
   }
    return 0;
}

答案 1 :(得分:1)

在输入houseprice的同时,如果indexes大于vector,则可以将price存储到100数组中。

live demo

#include <iostream>
#include <vector>

int main()
{
    std::size_t size; std::cin >> size;
    std::vector<std::size_t> indexVec;  // vector array to store the indexes
    std::size_t no_houses = 0;          // to count while inputing
    for (std::size_t index = 0; index < size; ++index)
    {
        int house, price;
        std::cin >> house >> price; // user input
        if (price > 100) 
        {
            ++no_houses;  
            indexVec.emplace_back(index + 1);  // store the indexes
        }
    }
    std::cout << no_houses << " "; // just print
    for (const int index: indexVec)     std::cout << index << " ";
}

答案 2 :(得分:1)

据我了解,您通过查看输出应该是什么以及您的代码为数组分配了许多不必要的内存来提出疑问。
6(可比较的房屋数量)? 房屋1(42 15) 而不是由100个元素组成的数组,您只需要2个元素,因为每个元素都是整数而不是价格 平方[2],在我的名字中将其称为“ house [0]”和“ house [1]” house [0]的值为42,house [1]的值为15。

它看起来也像是二维数组,因此您可以使用houseprice [6] [2]。 这将为您提供一个二维数组,如下所示:

[0] [0] [1]

[1] [0] [1]

[2] [0] [1]

[3] [0] [1]

[4] [0] [1]

[5] [0] [1]

这使第一列成为索引,第二和第三列成为要比较的房屋。 希望这可以帮助您理解数组以及如何做自己想做的事情。

idzireit

答案 3 :(得分:0)

您是否编译过代码?错误-i是什么?

您需要阅读以读取该行(两个数字),然后检查第一个数字是否大于100。如果是,则打印其索引,即i