在数组中添加元素将不接受类似的元素

时间:2018-03-10 14:55:18

标签: c++

我正在练习在数组中添加元素,并且我确实添加了一个while循环以防止在数组已经存在元素时添加,并且必须从数组中输入不同的字符。问题是,在我的例子中,我输入了一个字符' a'然后' b'在' b'之后我试图输入' a'再次,它接受了输入。它应该不接受已经存在的元素,但它确实如此。这是为什么?提前谢谢

这是我的代码

#include<iostream>

using namespace std;

int main(){

    char array[5] = {'a','a','a','b','b'};
    char add;

    for(int x = 0; x<5; x++){
            cout<<"[" <<array[x] <<"]";
        }
    cout<<endl;

    cout<<"Add element: ";
    cin>>add;

        //if the element is already existing, prompt user to input again
        for(int x =0 ;x<5;x++){
            while(add==array[x]){
            cout<<"Already Exist and its in position " <<x+1 <<" Please add a different character:  ";
            cin>>add;
            }

        }

    array[5] = add; //adding the element in the last position

    //if adding succesfull, display the new element
    cout<<"==========================================" <<endl;
    cout<<"Adding Succesful! Your new array is" <<endl;

        for(int x = 0; x<=5; x++){
            cout<<"[" <<array[x] <<"]";
        }

    cout<<endl;
    cout<<"==========================================" <<endl;
}

3 个答案:

答案 0 :(得分:2)

请改用std::set。它只允许插入一次项目,返回值将允许您知道是否插入了项目;

std::set<char> characters;
char item = 'a'; // read it from input or whatever you want instead.
auto result = characters.insert(itemToInsert);
if (!result.second) { display error message }

请参阅http://www.cplusplus.com/reference/set/set/insert/

如果您需要记住广告订单,那么您可以使用std::setstd::vector。使用第一个,很容易找到是否插入了一个项目。

请注意,在某些情况下,您只需使用std::vector成员函数在find()中进行线性搜索即可。如果预期的项目数量相对较小,实际上可能是最好的方法,特别是如果数据本身是一种简单的数据类型。

答案 1 :(得分:2)

问题出在你的while循环中。首先输入'a'。这会导致while循环开始,然后在输入'b'时结束。在这个阶段,你走出while循环,在for循环中x = x + 1。这次不使用循环,再次使用x = x + 1。当x = 3时,while循环再次打开,因为位置3的数组元素是'b'。当你在此之后输入'a'时,数组中剩下的唯一元素是'b'。所以它不会进入while循环。它取而代之的是所有循环并继续运行。

你可以通过干运行找到这个错误。尝试自己纠正它。否则,您可以看到我的解决方案,该解决方案适用于我测试的数据。

<强>解决方案:

        for(int x =0 ;x<5;x++)
        {
            if (add==array[x])
            {
                cout<<"Already Exist and its in position " <<x+1 <<" Please add a different character:  ";
                cin>>add;

                x=-1; //So that char 'add' is compared again with each element of the array.
            }

        }

答案 2 :(得分:0)

您应该pandas中的for i in range(0,5): pcnt=(df.loc[i, 'Marks'])/(df.loc[0, 'Marks']) df.loc[i, 'Percentage']=pcnt*100 。所以

x=0