[英]C++ Reading txt directly into a custom vector that should be grouped accordingly to the struct by each line
我正在使用自定義向量,當前代碼如下所示:
struct Edge {
int source, dest, weight;
};
int main()
{
// initialize edges as per the above diagram
// (u, v, w) represent edge from vertex `u` to vertex `v` having weight `w`
vector<Edge> edges =
{
{0, 1, 10}, {0, 4, 3}, {1, 2, 2}, {1, 4, 4}, {2, 3, 9},
{3, 2, 7}, {4, 1, 1}, {4, 2, 8}, {4, 3, 2}
};
// total number of nodes in the graph (labelled from 0 to 4)
int n = 5;
// construct graph
Graph graph(edges, n);
}
我想從使用硬編碼值更改為使用如下所示的.txt
文件:
0 1 2
0 2 3
0 3 3
1 2 4
如何切換到以與以前相同的方式獲取這些數字,但使用.txt
輸入而不是硬編碼數字?
我試過這樣的事情:
std::vector<std::string> vecOfStr;
bool result = getFileContent("my/path/to/file", vecOfStr);
std::vector<int> ints;
std::transform(vecOfStr.begin(), vecOfStr.end(), std::back_inserter(edges),
[&](std::string s) {
std::stringstream ss(s);
int i;
ss >> i;
return i;
});
for (auto &i: edges) {
//std::cout << i << ' ';
}
但沒有成功。
我有一個問題,因為從文件中讀取總是作為字符串,我需要以某種方式將每一行轉換為我的自定義結構。
題外話:順便說一句,這是一個 Dijkstra 算法尋路程序,為每個頂點尋找路徑...
我很抱歉這個問題是如何提出的。 我同意它沒有很好地解釋。 無論如何...我設法通過添加以下代碼來完成這項工作:
void readInstance(string filename, Instance &instance){
instance.instanceName = filename;
ifstream file(filename);
if (file.is_open()) {
string line;
int i = 0;
while (getline(file, line)) {
if(i == 0){
instance.n = stoi(line);
}
else{
istringstream ss(line);
string aux1, aux2, aux3;
ss >> aux1;
ss >> aux2;
ss >> aux3;
Edge p;
p.source = stod(aux1);
p.dest = stod(aux2);
p.weight = stod(aux3);
instance.Edges.push_back(p);
}
i++;
}
file.close();
}
else {
cout << "Error opening instance file" << endl;
exit(1);
}
}
假設您在文本文件中輸入了以下格式
0 1 2
0 2 3
0 3 3
1 2 4
您可以使用以下代碼將整數直接讀入向量中。 無需使用std::transform
將字符串轉換為整數。
#include <iostream>
#include <vector>
#include <fstream>
struct Edge {
int source, dest, weight;
};
std::ostream& operator<<(std::ostream& os, const Edge edge) {
os << "(" << edge.source << ", " << edge.dest << ", " << edge.weight << ")\n";
return os;
}
int main()
{
// initialize edges as per the above diagram
// (u, v, w) represent edge from vertex `u` to vertex `v` having weight `w`
std::vector<Edge> edges;
std::ifstream fin("in.txt");
if (!fin.is_open()) {
std::cerr << "fail";
return 1;
}
int s, d, w;
while (fin >> s >> d >> w) {
edges.emplace_back(Edge{s, d, w});
}
fin.close();
for (auto &edge: edges) {
std::cout << edge;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.