c++ 计算 txt 文件中每对元素的出现次数
c++ Count the occurrence of each pair of element in txt file
我有文本文件为:
41 2 3 4
33 1 2
3 4 2 1
2 4 3
其中每行中的第一个元素表示每行中元素的总数
我想计算每对元素的出现次数并打印结果,例如:
(1,2) = 3 次
所以我不需要计数和打印 (2,1)
最终结果必须是:
1 2 = 3
1 3 = 3
1 4 = 2
2 3 = 2
2 4 = 2
3 4 = 2
这是到目前为止的代码:
//global values:
int count2[10][10]; // to store the count of occurrence of each pair
int pair2[10][10];// to store the pair of element
int Totalnum; // total number of elements in txt file=4
int TotLines; // total number of lines in txt file=4
// main fun
int RowSize;
int item1, item2;
int maxSize = 0;
FILE *fp;
int i, j, k;
// Initialize
count2[10][10] = (int )malloc(sizeof(int)* Totalnum);
pair2[10][10] = (int )malloc(sizeof(int)* Totalnum);
if ((count2 == NULL) || (pair2 == NULL)) {
cout << "out of memoryn";
exit(1);
}
for (i = 0; i < Totalnum; i++)
for (j = 0; j < Totalnum; j++){
count2[i][j] = 0;
pair2[i][j] =0;
}
/* scan DB to count the frequency of each pair item */
if ((fp = fopen(dataFile, "r")) == NULL) // Database file
{
cout << "Can't open data file " << dataFile << "n";
exit(1);
}
/* Scan each line of the DB */
for (i = 0; i < TotLines; i++)
{
/* Read the row size */
fscanf(fp, "%d", &RowSize);
/* Read the items in the row*/
for (j = 0; j < RowSize; j++)
{
fscanf(fp, "%d", &item1);
for (k = j + 1; k < RowSize; k++)
{
fscanf(fp, "%d", &item2);
if (pair2[item1][item2] == pair2[item2][item1])
{
count2[item1][item2] ++;
count2[item2][item1] = count2[item1][item2];
}
else
count2[item1][item2]++;
}
}
}
fclose(fp);
for (j = 0; j <= Totalnum; j++){
for (k = j + 1; k <= Totalnum; k++)
printf("%d [%d] ", pair2[j][k], count2[j][k]);
cout << "n";
}
将
货币对映射到计数器要简单得多。下面是它的样子:
std::map<std::pair<int, int>, int> pairToCount;
while (in >> a >> b)
{
auto it = pairToCount.find(std::make_pair(b, a));
++pairToCount[
(it != pairToCount.end()) ? std::make_pair(b, a)
: std::make_pair(a, b) ];
}
for (const auto& p : pairToCount)
{
std::cout << "(" << p.first.first << " " << p.first.second << ") = "
<< p.second << 'n';
}
这是一个现场演示。
在开始计算货币对之前,您必须识别它们。
您的要求缺乏如何从数据行生成对。
示例 1,使用 4 1 2 3 4
这对是<1,2> <3,4>吗?
还是<1,2> <2,3> <3,4>?
或所有渗透:
<1, 1> <1, 2> <1, 3> <1, 4>,
<2, 1> <2, 2> <2, 3> <2, 4>,
<3, 1> <3, 2> <3, 3> <3, 4>,
<4, 1> <4, 2> <4, 3> <4, 4>?
一旦您决定如何生成货币对,使用std::map
将更容易计数。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 如何将 txt 文件中的行分隔为组件C++
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 计算TXT文件中元素的数量
- c++ 计算 txt 文件中每对元素的出现次数
- c++按元素编辑txt文件
- 如何从填充.txt文件名的向量中选取随机元素C++
- 矢量元素和 txt 文件行之间的字符串比较不起作用