为什么使用#define定义时却变得未定义[关闭]

问题描述 投票:0回答:1

我在我的 C++ 程序中使用

vector<int>
vi
定义为
#define
。但是当我尝试使用
vi
时,它显示
identifier "v" is undefinedC/C++(20)

我已经安装了mingw版本:g++.exe (MinGW.org GCC-6.3.0-1) 6.3.0 我使用 Visual Studio Code 作为我的代码编辑器。

这是我的代码:

#include <bits/stdc++.h>

using namespace std;

#define ll long long;
#define vi vector<int>;
#define all(v) v.begin(), v.end();
#define tle ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

void solution() {
  vi v;  // here I am getting error
}

int main() {
  tle;
  int test_case;
  cin >> test_case;
  while (test_case--) {
    solution();
  }

  return 0;
}

为什么我收到错误消息?怎么解决这个问题?

我期待得到解决方案或如何在我的 C++ 程序中使用 #define

c++ c-preprocessor
1个回答
0
投票

您面临的问题是由于代码中错误使用了

#define
宏造成的。定义宏时,不应在宏定义末尾包含分号 (
;
)。使用宏时要加分号。

#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define vi vector<int>
#define all(v) v.begin(), v.end()
#define tle ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

void solution() {
  vi v;  // No error now
}

int main() {
  tle;
  int test_case;
  cin >> test_case;
  while (test_case--) {
    solution();
  }
  return 0;
}

通过删除每个

#define
后面的分号,您已成功定义宏
ll
vi
all
,现在可以在代码中正确使用它们。分号只能在使用宏时使用,而不是在定义宏时使用。

通过此更改,错误“标识符‘v’未定义”应该得到解决,并且您的代码应该可以顺利编译。

© www.soinside.com 2019 - 2024. All rights reserved.