首页 > 解决方案 > 为什么这个数组的元素没有改变。我正在尝试创建一个标志数组来检查元素“x”是否存在?是新的 C++ 概念吗

问题描述

我想创建一个标志数组来查看一个元素是否存在。

输入:

2 1 4
+ 1
+ 2
- 1
- 2

期望的输出:

0 0 0  
0 0 0  
0 0 0 
#include <iostream>
#include <stdio.h>
using namespace std;

// Create a function 
// Function is passed with values n=2, m=1, q=4,
// and an array of string 
// where str[0] = "+ 1", str[1] = "+ 2", str[2] = "- 1", str[3] = "- 2"
void func(int n, int m, int q, string s[])
{
    // Create an array 
    int *array;
    array = new int[n + 1];
    
    // OUTPUT:: Print array element values to check elements
    for (int i = 0; i <= n; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;


    // Iterate over the string s[array]
    for (int i = 0; i < q; i++)
    {
        // Check if str[i] starts with '+'
        if (s[i][0] == '+')
        {
            
            // Set the index
            int index = s[i][2];
            
            // Set the array element to 1 to identify
            array[index] = 1;
            
            /*
            Check if "index is correct" and "array[index] is set to 1" ----- YES YES YES
            
            cout << "index is: " << s[i][2] << ". "
                 << "ptr[s[i][2]] is: " << ptr[index] << endl;
            */
            
            // OUTPUT:: Iterate over the array to see its elements
            for (int j = 0; j <= n; j++)
            {
                cout << array[j] << " ";
            }
            cout << endl;
        }
    }
}

int main()
{
    int n, m, q;
    cin >> n >> m >> q;
    cin.ignore();
    string str[q];

    for (int i = 0; i < q; i++)
    {
        getline(cin, str[i]);
    }

    func(n, m, q, str);

    return 0;
}

请检查一下。我通过在上面的代码中编写注释来简化它。

我是 C++ 新手,不明白为什么数组元素没有更改为 1。

无论是新的 C++ 概念,还是我的代码有错误。据我所知,它应该工作。但它不起作用。

标签: c++arrays

解决方案


推荐阅读