首页 > 解决方案 > 以下 c++ 代码在 leetcode 中有效,但在我的 vscode 中无效,为什么?

问题描述

我目前正在研究一个 leetcode 问题,并尝试在我的最后追踪代码过程,这是我的解决方案:

#include <iostream>
#include <vector>
#include <stack>
#include <utility>

using namespace std;

vector<int> direction{-1, 0, 1, 0, -1};

int maxAreaOfIsland(vector<vector<int>>&grid){

  int m = grid.size(), n = m ? grid[0].size() : 0, local_area, area = 0, x, y;
  for (int i = 0; i < m; ++i){

    for (int j = 0; j < n; ++j){

      if(grid[i][j]){
        local_area = 1;
        grid[i][j] = 0;
        stack<pair<int, int>> island;
        island.push({i, j});
        while(!island.empty()){
          auto [r, c] = island.top(); \\problem line, vscode can't understand it
          island.pop();
          for (int k = 0; k < 4; ++k){
            x = r + direction[k], y = c + direction[k + 1];
            if(x>=0 && x<m && y>=0 && y<n && grid[x][y]==1){
              grid[x][y] = 0;
              ++local_area;
              island.push({x, y});
            }
          }
        }
        area = max(area, local_area);
      }

    }
  }

  return area;
}

此代码在 leetcode 方面有效,但不是我的,这是警告

[Running] cd "c:\Users\chen1\OneDrive\Desktop\C_C++tut\" && g++ leetcode695.cpp -o leetcode695 && "c:\Users\chen1\OneDrive\Desktop\C_C++tut\"leetcode695
leetcode695.cpp: In function 'int maxAreaOfIsland(std::vector<std::vector<int> >&)':
leetcode695.cpp:23:16: warning: structured bindings only available with -std=c++17 or -std=gnu++17
           auto [r, c] = island.top();
                ^
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

[Done] exited with code=1 in 0.932 seconds

有人可以解释为什么,虽然我有另一种方法来替换它,但它仍然很烦人和令人困惑

谢谢你的帮助

此外!!!我实际上有我的主要功能;这里的问题是一个语法错误,leetcode的编译器识别它,但不是g ++,导致问题的行是auto [r, c] = island.top();,如果我将它更改为

int r = get<0>(island.top());
int c = get<1>(island.top());

那么它工作正常,我只是不明白为什么leetcode编译器可以理解它,但不是g ++

标签: c++

解决方案


链接器错误(不是警告)是导致构建失败的原因(横向滚动!):

[...]crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'

当您的代码缺少 amain()WinMain()入口点时,会在 MinGW gcc 中发生。就像你的那样。我猜 leetcode(我从未听说过或使用过)为您提供了一个测试工具来运行该功能?它编译 - 消息是一个链接器错误,所以它不能形成一个可执行文件 - 你需要一个main().

关于警告,您需要再次滚动到消息的末尾:

leetcode695.cpp:23:16: warning: structured bindings only available 
                                with -std=c++17 or -std=gnu++17
           auto [r, c] = island.top();

可以通过指定 C++17(或更高版本)编译(或不使用结构化绑定)来解决。在G++ Compiler warning when using c++ 17 updates中讨论了 Windows/VSCode 特定的解决方案,但基本上它是关于设置编译器开关-std=c++17


推荐阅读