如何解决这个问题? 显示基思错误



我正在编写一个简单的c ++程序

#include <bits/stdc++.h>
#define ll long long
#define ul unsigned long long
#define ld long double
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define repi(i, a, b) for (int i = (a); i > (b); i--)
#define all(x) x.begin(), x.end()
#define ks(x) (cout << #x << ":" << (x) << 'n')
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
#define gcd _gcd
using namespace std;
const ll mod = 1000000007;
int main()
{
fastio;
ll tc = 1;
cin >> tc;
for (ll t = 0; t < tc; t++)
{
ll n;
cin >> n;
string s;
cin >> s;
ll cnt = 0;
ll i = n - 1;
if (s[n - 1] == ')')
{
i--;
cnt++;
while (s[i] == ')' && i > -1)
{
i--;
cnt++;
}
}
if (cnt > n / 2)
cout << "YESn";
else
{
cout << "NOn";
}
}
return 0;
}

并输入*

5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)*

但它显示输出我无法理解,请帮助

/

home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++-v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::参考 std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [_CharT = char; _Traits = std::char_traits; _Alloc = std::分配器; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = 字符&;std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = 无符号 int]:断言 '__pos <= size()' 失败。

这是错误的

while (s[i] == ')' && i > -1)

它应该是

while (i > -1 && s[i] == ')')

如果 i 等于 -1,那么在第一个版本中,s[i]会给出您可以看到的错误。但是在第二个版本中,首先评估i > -1,因为它是错误的,所以s[i]不会被评估,因此不会导致错误。

这里还有一个重要的教训。该程序可在您的朋友机器上运行,但并非每个有错误的程序都失败。它甚至可能看起来运行正常。

断言__pos <= size()意味着您正在使用末尾的 [] 运算符访问字符串 s。 在调试器中运行程序,并在索引> size() 上设置条件断点,或者只检查每次访问。

s
  1. 和 n 都是从 cin 读取的(与 n = s.size() 相反),如果 n> s.size() + 2 应该触发它。
  2. n 是类型(有符号)长整型长整型
  3. ,运算符 [] 需要size_t(无符号长整型),因此 n <= 0 也可能触发此类型(有符号)长整型
  4. 在你的while循环中,你s[i] == ')' && i > -1i = -1将首先尝试访问s[-1],然后再检查i > -1作为&&运算符作为从左到右的关联性。

最新更新