C 补充错误:“ =”令牌之前的预期初始化器

C++ Complie Error: expected initializer before ‘+=’ token

本文关键字:初始化 令牌 错误      更新时间:2023-10-16

我正在尝试创建图形存储的矢量列表。这是我的代码

#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

我已经在网站上环顾了,我不知道这个错误是什么意思。谢谢!

您遇到的错误是因为您试图重新宣布已声明的变量。因此,从您的示例中:

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
}