用C++读取一个带有行名和列名的矩阵然后按照行名将矩阵进行分组。将每一组中除了行名以外的数值不为0的位置记录下来。
以下是一个用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); // 读取第一行,即列名
while (getline(inputFile, line)) {
string rowName;
inputFile >> rowName; // 读取每行的行名
vector<pair<int, int>> nonZeroPositions; // 存储每组中除了行名以外数值不为0的位置
int value;
for (int col = 0; col < line.size(); col++) {
inputFile >> value;
if (value != 0) {
nonZeroPositions.push_back(make_pair(row, col));
}
}
groups[rowName] = nonZeroPositions; // 将分组结果存入map中
}
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"的文本文件中,每行的格式为:行名 数值1 数值2 ...。你需要根据实际情况修改文件名和文件格式。
此代码使用了map<string, vector<pair<int, int>>>来存储分组结果,其中string表示行名,vector<pair<int, int>>>表示每组中非零数值的位置,即行号和列号。代码最后会输出每组的行名和非零数值的位置。
原文地址: https://www.cveoy.top/t/topic/iuip 著作权归作者所有。请勿转载和采集!