比较两个向量中的未排序元素

Comparing unsorted elements in two vectors

本文关键字:排序 元素 向量 两个 比较      更新时间:2023-10-16

我是C++新手,我正在尝试将两个未排序的向量元素相互比较并确定它们是否匹配。

例如:1 4 9 16 9 7 4 9 11 和 11 11 7 9 16 4 1这些将被视为匹配。

我尝试使用 firstVector == secondVector,但是当它们的向量未排序时,这不起作用,我专门尝试在它们未排序但正在挣扎时比较它们。

int main() {
int incorrectMatches = 0;
int totalMatches = 0;
int input = 0;
vector <int> firstVector;
vector <int> secondVector;
do {
    cout << "Please enter a number for first vector:  ";
    cin >> input;
    firstVector.push_back(input);
    cout << endl;
} 
while (input > 0);
input = 0;
firstVector.pop_back();
do {
    cout << "Please enter a number for second vector: ";
    cin >> input;
    secondVector.push_back(input);
    cout << endl;
} 
while (input > 0);

secondVector.pop_back();

for (int loop = 0; loop < firstVector.size(); loop++) {
    cout << firstVector[loop] << " ";
}
cout << endl;
for (int loop = 0; loop < secondVector.size(); loop++) {
    cout << secondVector[loop] << " ";
}
cout << endl;
int vectorSize = firstVector.size();
for (int i = 0; i < vectorSize; i++) {
    if (firstVector[i] == secondVector[i]) {
        totalMatches = totalMatches++;
    }
    else {
        incorrectMatches = incorrectMatches++;
    }
}
cout << "There were " << totalMatches << " matches." << endl;
cout << "There were " << incorrectMatches << " incorrect matches";
/*
if (firstVector == secondVector) {
    cout << "Your vectors match!";
}
else{
    cout << "Your vectors don't match!";
}
*/
/*
for (int i = 0; i < input; i++) {
    cout << "Please enter a number (1-9): ";
    myVector.push_back(input);
    cout << endl;
    myVector[i] = i;
    cout << "Vector entry: " << myVector[i] << endl;
}
*/
system("pause");
return 0;}

由于重复无关紧要,您可以简单地将向量的元素分别插入单独的std::set中,然后使用 operator == 比较集合。我认为集合的使用最能表达您的程序的意图:

int main() {
    vector<int> v1 =  { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
    vector<int> v2 =  { 11, 11, 7, 9, 16, 4, 1 };
    set<int> s1;
    s1.insert(v1.begin(), v1.end());
    set<int> s2;
    s2.insert(v2.begin(), v2.end());
    bool isEqual = (s1 == s2);
    cout << "v1 and v2 are " << (isEqual ? "" : "not ") << "equal." << endl;
    return 0;
}