下面的程序计算CA整数的频率以阵列如何,因为字符串也是在后端阵列适用于字符串变量这个概念
using namespace std;
int counter[10]={0,0,0,0,0,0,0,0,0,0};
int arr [9][9],x;
int main()
{
srand(time(NULL));
cout<<"enter the array \n";
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
arr[i][j]=rand()%10;
}
}
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
counter[arr[i][j]]++;
}
}
for(int j=0;j<10;j++){
cout<<j<<" : "<< counter[j]<<endl;
}
return 0;
}
这里有一个如何从什么指望任何事情发生:
#include <iterator>
#include <map>
#include <algorithm>
template<class InputIt>
auto
occurrences(InputIt begin, InputIt end)
{
std::map<typename std::iterator_traits<InputIt>::value_type, std::size_t> result;
std::for_each(begin, end, [&result](auto const& item){ ++result[item]; });
return result;
}
#include <string>
#include <iostream>
int main()
{
auto text = std::string{"Hello, World!"};
auto occ = occurrences(begin(text), end(text));
std::cout << occ['l'] << '\n'; // outputs 3
}
template<class InputIt>
这是对任何输入迭代一个通用的(模板)功能迭代。
auto
它的返回类型是从它的实现推断。剧透:它(值计数器,这个值的出现)的std::map
。
occurrences(InputIt begin, InputIt end)
occurrences
被称为一对夫妇迭代器定义范围,通常调用begin(C)
和end(C)
你的容器C
。
std::for_each(begin, end, //...
对于范围内的每个元素...
[&result](auto const& item){ //...
......请执行以下处理...
++result[item]; });
...递增发生次数的数值item
,从零开始如果第一。
这不是因为它拷贝它的计算值的高效实现。对于整数,字符等,其完美但对于复杂的类型,你可能想提高这个实现。
这是通用的,标准集装箱兼容。你可以指望任何迭代。
如果我理解正确的话,你要计算的字符串的出现。 STL容器地图是用于这一目的。以下是示例代码。
#include<iostream>
#include<map>
#include<string>
#include<vector>
int main()
{
std::vector<std::string> arrayString;
std::map<std::string, int> counter;
std::map<std::string, int>::iterator it;
arrayString.push_back("Hello");
arrayString.push_back("World");
arrayString.push_back("Hello");
arrayString.push_back("Around");
arrayString.push_back("the");
arrayString.push_back("World");
// Counting logic
for(std::string strVal : arrayString)
{
it = counter.find(strVal);
if(it != counter.end())
it->second += 1; // increment count
else
counter.insert(std::pair<std::string, int>(strVal, 1)); // first occurrence
}
// Results
for(std::map<std::string, int>::iterator it = counter.begin(); it != counter.end(); ++it)
std::cout << it->first << ": " << it->second << std::endl;
return 0;
}
写计数逻辑更紧凑的方式是:
// Counting logic
for(std::string strVal : arrayString)
{
++counter[strVal]; // first time -> init to 0 and increment
}