我试图在两个数组之间打印非常见元素.例如,如果array1 = {1,3,5}并且array2 = {1,2,4,5},则我的输出应为{2,3,4}.
我在这里试了一下.但它只打印3.我做错了什么?
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1, 3, 5 };
int b[] = { 1, 2, 4, 5 };
bool contains = false;
int result[10];
int r = 0;
int x;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if (a[i] == b[j]) {
contains = true;
break;
}
}
if (!contains) {
result[r]=a[i];
++r;
}
else{
contains = false;
}
}
for (x = 0; x < r; x++)
{
cout<< result[x]<<"\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你没有从加入特殊的值b来result.但这是c ++.我推荐使用std::vector,std::sort,std::set_symmetric_difference和std::back_inserter.
#include <iostream> // std::cout
#include <algorithm> // std::set_symmetric_difference, std::sort
#include <iterator> // std::back_inserter
#include <vector> // std::vector
int main()
{
std::vector< int > a = { 1, 3, 5 };
std::vector< int > b = { 1, 2, 4, 5 };
std::sort( a.begin(), a.end() );
std::sort( b.begin(), b.end() );
std::vector< int > result;
std::set_symmetric_difference( a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(result) );
for ( int x : result )
std::cout << x << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如在下面的评论建议的@ChristianHackl,还可以使用数组a和b使用自由站立功能std::begin和std::end:
#include <iostream> // std::cout
#include <algorithm> // std::set_symmetric_difference, std::sort
#include <iterator> // std::back_inserter
#include <vector> // std::vector, std::begin, std::end
int main()
{
int a[]{ 1, 3, 5 };
int b[]{ 1, 2, 4, 5 };
std::sort( std::begin(a), std::end(a) );
std::sort( std::begin(b), std::end(b) );
std::vector< int > result;
std::set_symmetric_difference( std::begin(a), std::end(a), std::begin(b), std::end(b), std::back_inserter(result) );
for ( int x : result )
std::cout << x << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)