我是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;}
答案 0 :(得分:2)
由于重复无关紧要,您可以分别在单独的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;
}