我正在尝试创建一个存储图表邻接列表的向量。这是我的代码
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<vector<int>> G; // the adjacency list
void readAdj(char* file){
fstream inf;
inf.open(file);
string line;
// Get each adjancency list for each vertice and map it to it's corresponding location in G
while (getline(inf,line).good()) { // Each adjancency list is stored as a line
vector<int> adjList;
string adjV = ""; // Adjacency value to vertex v
// Create adjacency list for current line
for (int i = 0; i < line.size(); i++) {
if (line[i] != ' ') {
string adjV += line[i]; // Build the string each non-space iteration
}
else { // Space found, add the now complete string to the adjancency array
adjList.push_back(stoi(adjV)); // Add the character to the list as an int
adjV = ""; // Reset adjv for next iteration
}
G.push_back(adjList);
}
inf.close();
}
这是我得到的错误:
GraphProcessor.cpp: In function ‘void readAdj(char*)’:
GraphProcessor.cpp:27:21: error: expected initializer before ‘+=’ token
string adjV += line[i]; // Build the string each non-space iteration
我在网站上四处看看,我不知道这个错误意味着什么。谢谢!
答案 0 :(得分:0)
您遇到的错误是因为您正在尝试重新声明已声明的变量。所以从你的例子来看:
void readAdj(char* file){
fstream inf;
inf.open(file);
string line;
while (getline(inf,line).good()) {
vector<int> adjList;
string adjV = ""; // Here you declare the adjV string
// Create adjacency list for current line
for (int i = 0; i < line.size(); i++) {
if (line[i] != ' ') {
// Here you are trying to redeclare the adjV variable
// string adjV += line[i];
adjV += line[i]; // All you need to write is this
} else {
adjList.push_back(stoi(adjV)); // Add the character to the list as an int
adjV = ""; // Reset adjv for next iteration
}
G.push_back(adjList);
}
// You don't need to close the file.
// It closes automatically at the end of scope the variable was opened in
// Which is exactly here
}