c++ - 一个变量的输入值也被保存到另一个变量中
问题描述
在下面关于称为get_array()
问题的方法的代码中,由于capacity
变量在用户在控制台中首次输入后更改为,并且capacity
值分配给用户给出的值
我不确定发生了什么,但这让我很恼火,还是我错过了一些基本知识?请帮忙
#软件
我正在使用CodeBlocks v17.12
#操作系统
Windows 10 家庭版
#include <iostream>
using namespace std;
class LinearSearch
{
int my_arr[];
int capacity, c, val;
public:
LinearSearch()
{
this->capacity = 0;
this->c = 0;
this->val = 0;
}
void get_array()
{
cout << "Define number of elements in the array: ";
cin >> this->capacity;
for( int i = 0; i < this->capacity; i++ )
{
cout << "Enter value " << i+1 << " - " << this->capacity << " : ";
cin >> this->my_arr[i];
}
for( int k = 0; k < capacity; k++ )
{
cout << my_arr[k] << endl;
}
cout << endl;
}
void search_value()
{
cout << endl << "Enter a value to search: ";
cin >> this->val;
for(int j = 0; j < capacity; j++)
{
if(my_arr[j]==val)
{
cout << endl << this->val << " value found in the array at index array[" << j << "] value number " << j+1 << "." << endl << endl;
c++;
break;
}
}
if(this->c==0)
cout<<endl<<this->val<<" value not found in the array."<<endl<<endl;
}
};
int main()
{
int choice;
LinearSearch obj;
while( true )
{
cout << "0) Exit\n1) Insert Data\n2) Search Data\n\nEnter Option: ";
cin >> choice;
switch( choice )
{
case 0:
return 0;
case 1:
obj.get_array();
break;
case 2:
obj.search_value();
break;
default:
cout << "\nWrong Option!!\n\n";
break;
}
}
return 0;
}
解决方案
int my_arr[];
不是有效的标准 C++,即使在 C 中,它也只能作为所谓的灵活数组成员出现在成员列表的末尾。
你应该std::vector<int> my_arr;
改用。(需要#include<vector>
。)
然后,您可以使用 向其中添加新元素,也my_arr.push_back(/*some number here*/);
可以使用 调整数组的大小my_arr.resize(/*new size here*/);
。
推荐阅读
- c - 如何在数组的括号之间填充,我可以使用 strlen 吗?
- javascript - 使用 step() 在 $.animate 中不使用选择器停止所有其他动画?
- css - @media CSS 仅在纵向模式下不工作的问题?
- node.js - 一块流占用的内存
- java - 如何使用他们的字体在 textview 中复制文本?
- java - Java 超出 2 个字节
- c# - 将 winforms 设计器中的字体设置为 Font 对象
- ruby - Rails - 将数字转换为数组
- c++ - c ++,打印列表内对象的属性值,查找属性特定值的对象,删除对象
- firebase - 如何仅允许访问我的 nativescript 应用程序的 firestore 数据?