C++中给定范围内具有相等元素的索引数
在本教程中,我们将编写一个程序来计算给定范围内具有相等元素的索引数量。
您将获得一个数组和索引范围。您需要计算给定范围内相等的相邻元素的总数。
让我们看看解决问题的步骤。
初始化数组和索引范围。
编写一个循环,从范围的下索引到范围的上索引进行迭代。
将元素与上一个或下一个元素进行比较。
如果它们相等,则增加计数。
返回计数。
示例
让我们看看代码。
#include输出结果using namespace std; int getEqualElementsCount(int arr[], int n, int lower, int upper) { int count = 0; for (int i = lower; i < upper; i++) { if (arr[i] == arr[i + 1]) { count += 1; } } return count; } int main() { int arr[] = { 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5 }; int n = 15; cout << getEqualElementsCount(arr, 15, 1, 15) << endl; return 0; }
如果你运行上面的代码,那么你会得到下面的结果。
10
结论
如果您对本教程有任何疑问,请在评论部分提及。