天天看點

c++在數組中查找元素并傳回位置下标,統計某元素出現次數程式

IDE是VS2013.

在數組中查找元素并傳回位置下标,若找到元素則傳回下标(多個相同元素,傳回最後一個),沒找到傳回-1;

統計某元素出現次數程式,沒出現傳回0;

#include "stdafx.h"
#include<iostream>
using namespace std;
int find(int ar[], int n, int element)//查找元素并傳回位置下标,find(數組,長度,元素)
{
	int i = 0;
	int index=-1;//原始下标,沒找到元素傳回-1
	for (i = 0; i <n; i++)
	{
		if (element ==ar[i])
		{
			index=i;//記錄元素下标
		}
	}
	return index;//傳回下标
}
int frequency(int ar[], int n, int element)//統計某元素出現次數(數組,長度,元素)
{
	int i = 0;
	int count= 0;//出現次數
	for (i = 0; i <n; i++)
	{
		if (element == ar[i])
		{
			count++;
		}
	}
	return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
	int a[6] = { 1, 2, 3, 4,5,5 };
	int index = find(a, 6, 4);//下标,查找元素4的下标
	int count= frequency(a, 6, 5);//次數,查找元素5出現的次數
	cout <<index<< endl;
	cout << count<<endl;
	system("pause");
	return 0;
}
           

運作結果:

c++在數組中查找元素并傳回位置下标,統計某元素出現次數程式

下面用c++函數模闆實作上面的程式。可以在int、float、double、char、string等類型數組裡實作功能。

#include "stdafx.h"
#include<iostream>
using namespace std;
template<typename T>
int find(T ar[], int n, T element)//查找元素并傳回位置下标,find(數組,長度,元素)
{
	int i = 0;
	int index=-1;//原始下标,沒找到元素傳回-1
	for (i = 0; i <n; i++)
	{
		if (element ==ar[i])
		{
			index=i;//記錄元素下标
		}
	}
	return index;//傳回下标
}
template<typename T>
int frequency(T ar[], int n,T element)//統計某元素出現次數,frequency(數組,長度,元素)
{
	int i = 0;
	int count = 0;//出現次數
	for (i = 0; i <n; i++)
	{
		if (element == ar[i])
		{
			count++;//次數+1
		}
	}
	return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
	string s[6] = { "ab", "cd", "ef", "gh", "ij", "ij" };
	int index = find<string>(s, 6,"cd");下标,查找字元串"cd"的下标
	int count = frequency<string>(s, 6, "ij");//次數,查找字元串"ij"出現的次數
	cout << index<<endl;
	cout <<count<< endl;
	system("pause");
	return 0;
}
           

運作結果:

c++在數組中查找元素并傳回位置下标,統計某元素出現次數程式

繼續閱讀