c++ - 为什么这个数组的元素没有改变。我正在尝试创建一个标志数组来检查元素“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++ 概念,还是我的代码有错误。据我所知,它应该工作。但它不起作用。
解决方案
推荐阅读
- json - SQL Server 抱怨无效的 json
- python - 调整程序窗口大小后如何捕捉宽度和高度(tkinter)
- r - 计算 R 中的滚动总和
- jquery - jQuery动态数字比较
- php - 将用户元从 Worpdress 网站克隆到目标网站
- assembly - 如何在 Assembly 中混洗数据
- r - 在数据帧的不同十分位数之间随机交换数据帧值
- r - 如何在 RStudio 中将字符转换为日期?
- javascript - 如何使用 promise 和 forEach 循环遍历 mongoDB?我想填充一个数组
- php - 如何使用单个查询更新表中的多条记录?(postgresql)