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

时间:2015-04-15 00:13:56

标签: c++

我是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]<< " ";
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以在推送之前使用字符串比较来检查它。这是因为你想检查字符串是否唯一,而不是你在每个字符串中共享单词(这稍微复杂一些。)

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/

答案 2 :(得分:0)

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

让我们看一下std::set here

  

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库几乎总是比自己做的更好!

这是一个实时example