假设我们有一个包含以下数据的.txt文件:
6
Paris New_York 1
London Berlin 1
Moskow Kiev 1
Paris London 1
New_York Moscow 1
其中6是城市数量,而不是意味着巴黎和纽约与价值1相关联,它将始终为1.
现在我想把它变成2D动态数组。我用这样的数字做了,但我不知道怎么用字符串做这个。 对于数字:
ifstream myfile("info.txt");
if (myfile.is_open()) {
getline(myfile, line);
istringstream(line) >> Number;
}
int **matrix= new int*[Number];
for (int i = 0; i < Number; i++) {
matrix[i] = new int[Number];
}
while (getline(myfile, line)) {
cout << line << '\n';
std::stringstream linestream(line);
int row;
int column;
int value;
if (linestream >> row >> column >> value)
{
a[row-1][column-1] = value;
a[column-1][row-1] = value;// mirror
}
那我怎么能为字符串做这个呢? 感谢您的有用答案
答案 0 :(得分:1)
在矩阵旁边需要unordered_map<string, int>
来将字符串映射到索引。这是我的解决方案:
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <unordered_map>
using namespace std;
int main() {
string line;
int Number;
ifstream myfile("info.txt");
if (myfile.is_open()) {
getline(myfile, line);
istringstream(line) >> Number;
}
int **matrix= new int*[Number];
for (int i = 0; i < Number; i++) {
matrix[i] = new int[Number](); // note () at the end for initialization to 0
}
unordered_map<string, int> citiesMap; // to map cities (string) to indexes (int)
int cityIndex = 0;
while (getline(myfile, line)){
std::stringstream linestream(line);
string row;
string column;
int value;
if (linestream >> row >> column >> value) {
if(citiesMap.find(row) == citiesMap.cend())
citiesMap[row] = cityIndex++; // add city to the map if it doesn't exist
if(citiesMap.find(column) == citiesMap.cend())
citiesMap[column] = cityIndex++; // add city to the map if it doesn't exist
matrix[citiesMap[row]][citiesMap[column]] = value;
matrix[citiesMap[column]][citiesMap[row]] = value;// mirror
}
}
for(auto x: citiesMap) {
cout << x.first << ": " << x.second << endl;
}
cout << endl;
for(int i = 0; i < Number; i++) {
for(int j = 0; j < Number; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// matrix should be freed here
}
您可以选择将唯一城市保存在矢量(或数组)中,以便从索引中访问城市。不要忘记释放记忆。此外,您可以使用std :: array作为矩阵,而不必担心内存问题。