C++实现:按行名分组矩阵并记录非零元素位置
C++实现:按行名分组矩阵并记录非零元素位置
在数据处理和分析中,我们经常需要对矩阵进行分组操作,并提取每组中特定元素的信息。
以下C++代码演示如何读取一个带有行名和列名的矩阵,并按行名进行分组,同时记录每组中除行名以外数值不为0的元素位置。
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace std;
int main() {
ifstream inputFile('matrix.txt'); // 假设矩阵保存在名为matrix.txt的文件中
if (!inputFile) {
cout << '无法打开文件' << endl;
return 1;
}
map<string, vector<pair<int, int>>> groups; // 用于存储分组结果
string line;
getline(inputFile, line); // 读取第一行,即列名
int row = 1; // 从第二行开始是数据,行号从1开始
while (getline(inputFile, line)) {
string rowName;
inputFile >> rowName; // 读取每行的行名
vector<pair<int, int>> nonZeroPositions; // 存储每组中除了行名以外数值不为0的位置
int value;
int col = 0;
// 循环读取每行数据
while (inputFile >> value) {
if (value != 0) {
nonZeroPositions.push_back(make_pair(row, col));
}
col++;
}
groups[rowName] = nonZeroPositions; // 将分组结果存入map中
row++;
}
inputFile.close();
// 输出分组结果
for (auto it = groups.begin(); it != groups.end(); ++it) {
cout << '分组:' << it->first << endl;
cout << '非零位置:';
for (auto p : it->second) {
cout << '(' << p.first << ', ' << p.second << ') ';
}
cout << endl;
}
return 0;
}
代码解释:
- 读取数据: 代码首先打开名为'matrix.txt'的文件,并读取文件内容。
- 数据结构: 使用
map<string, vector<pair<int, int>>>存储分组结果,其中:string:表示行名。vector<pair<int, int>>:表示每组中非零元素的位置信息,用pair存储行号和列号。
- 分组逻辑: 遍历每一行数据,读取行名和数值。
- 记录位置: 如果数值不为0,则记录其行号和列号。
- 输出结果: 最后,代码遍历
map并输出每个分组的行名以及非零元素位置。
注意事项:
- 代码假设矩阵数据存储在名为 'matrix.txt' 的文本文件中,且每行的格式为:行名 数值1 数值2 ...。
- 你需要根据实际情况修改文件名和文件格式。
希望这段代码能够帮助你理解如何使用C++读取、分组矩阵数据,并提取非零元素位置信息。
原文地址: https://www.cveoy.top/t/topic/fxsA 著作权归作者所有。请勿转载和采集!