比较两个向量中的未排序元素
Comparing unsorted elements in two vectors
我是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;
}
相关文章:
- 查找两个排序向量中共有的元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 将一系列已排序的元素划分为相邻组
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何在保持它们连接到同一元素的同时对 2 个数组进行排序?
- C++:结构与用于排序元素的函数
- 无法在阵列中重新排序元素-rapidjson
- 比较两个向量中的未排序元素
- 我如何在队列中排序元素
- c++中的Hashmap不排序元素
- c++插入排序元素