检查数组中的值是否已存在

check if value inside array already exists

本文关键字:是否 存在 数组 检查      更新时间:2023-10-16

我是C++的初学者。这是我上大学的第一年。我完全坚持了这一点。我必须制作一个接受输入 4 个字符串的程序,然后检查某个值是否已经存在,如果存在,则输出值存在,仅此而已,如果它们都是唯一的(所有 4 个字符串),则按升序输出它们。下面的代码有效,它已经按升序输出它们,但是如何在编写值之前找到值是否重复?

对不起我的坏英语家伙,我希望你明白我在这里想说什么

string name[4];
string temp;
for(int i=0;i<4;i++){
    cout<<"Enter "<<i+1<<" string"<<endl;
    getline(cin,name[i]);
}
for(int i=0;i<4;i++){
    for(int j=i+1;j<4;j++){
        if(name[i]>name[j]){
            temp=name[i];
            name[i]=name[j];
            name[j]=temp; 
        }
    }
}
for(int i=0; i<4; i++){
    cout<<name[i]<< " ";
}

您可以使用字符串比较在推送之前对其进行检查。这是如果你想检查字符串是否唯一,而不是如果你在每个字符串中有共享的单词(这稍微复杂一些。

string name[4];
string temp;
for(int i=0;i<4;i++)
{
    cout<<"Enter "<<i+1<<" string"<<endl;
    getline(cin,name[i]);
}
int failed = 0;
for(int i = 0;i<4;i++)
{
    for(int j=0;j<i;j++)
    {        
        // Check if the string is the same as any previous strings.
        if (name[i].compare(name[j]) != 0)
        {
             failed = 1;
             cout<<"String exists multiple times: "<<name[i];
        }
    }
}
// Check if there were any shared strings
if(failed==0)
{
   for(int i=0; i<4; i++)
   {
       cout<<name[i]<< " ";
   }
}

参考:http://www.cplusplus.com/reference/string/string/compare/

所以最好的方法是使用更好的容器!

让我们来看看这里的std::set

std::set 是一个关联容器,其中包含一组排序的 独特的对象。

那么我们如何才能最好地使用它,有很多例子,但我们可以看看你的特定例子。

#include <set> // For Set
int main() {
    set<string> names; // our fun easy ordered set.
    string name; // a name to read in
    unsigned int nameCounter = 0; // a counter
    // loop until we have 4 correct names. 
    while (nameCounter < 4) {
        cout<<"Enter "<<nameCounter+1<<" name"<<endl;
        getline(cin,name);
        // Check that when they enter it into the set that it is actually inserted.
        // Here we are being clever because "insert" returns a tuple with a bool
        // to tell us if we put it in correctly. 
        if (!names.insert(name).second) {
            cout << "That was not unique!" << endl;
        } else {
            nameCounter++;
        }
    }
    // Now we can loop through the names which is already sorted for us!
    for (auto listName : names) {
            cout << listName << " ";
    }
    cout << endl;
}

这不是那么容易吗!?利用std库几乎总是比自己做事更好!

这是一个活生生的例子。

for(int i=0;i<4;i++){
    for(int j=0;j<4;j++){
        if((name[i]==name[j]) && (i!=j)){
            cout<<"already exits";
        }