该解决方案在第 7 行执行时出现错误 'out of bounds'

The solution is executed with error 'out of bounds' on the line 7

虽然示例输入和输出匹配,但我收到了这个绑定错误。我尝试了几种方法来解决这个错误,但我做不到。请帮助我克服这个问题。也请解释为什么这个错误的主要原因是什么。 我的代码:

#include <iostream>
using namespace std;

int main(){
    int a[4];
    for(int i=1; i<=4; i++){
        cin >> a[i];
    }
    string s;
    cin >> s;

    int sum = 0;
    for(int i =0; i<s.size(); i++){
        if(s[i]=='1'){
            sum=sum+a[1];
        }
        else if(s[i]=='2'){
            sum+=a[2];
        }
        else if(s[i]=='3'){
            sum+=a[3];
        }
        else if(s[i]=='4'){
            sum+=a[4];
        }
    }
    cout << sum << endl;
}

示例输入:

1 2 3 4
123214

输出:

13

数组索引从 0 开始,因此 a[4] 在您的情况下超出范围。\

既然我们在这里,我建议不要使用 C 数组。请改用 std::arraystd::vector

另外最好使用 range for.

int a[4];
    for(int i=1; i<=4; i++){

a 的变量声明分配了索引 0 到 3(总共 4 个元素),但您正试图通过 i

访问 0 到 4

首先,这是不正确的

int a[4];
for(int i=1; i<=4; i++){
    cin >> a[i];
}

C++ 中的数组是从 0 开始索引的,所以如果你想 a[1] = 1

int a[5];
for(int i = 0; i < 5; i++){
    cin >> a[i];
}

旁注。您不需要“look-up 数组”。要对数字求和,您可以这样做:

sum += (s[i] - '0');