c++ - Ordering an array of strings while avoiding duplicates -
so have:
string array1[5] = {"a", "b", "c", "d", "f"}; string array2[5] = {"a", "c", "g", "f", "d"}; string result[100];
i'm trying make string result[100] compose of non-duplicates array1 , array2 while being in sequential order of array1[0] array2[0] array1[1] array2[1] etc.
(e.g.) string result[100] = {"a", "b", "c", "g", "d", "f"};
this code have far:
for (i=0; < 5; i++) { result[i] = array2[i]; } (i=0; i<5; i++) { (j=0; j<100; j++) { if (result[j] == "") { result[j] = array1[i]; break; } if (result[j] == array1[i]) break; } }
this code avoids duplicates, not in correct order want. can't wrap head around solving this. appreciated.
fully working, wrote.
#include <iostream> #include <string> #include <vector> using namespace std; int main(){ string array1[5]= {"a","b","c","d","f"}; string array2[5]= {"a","c","g","f","d"}; vector<string> result; bool check1; bool check2; for(int i=0; i<sizeof(array1)/sizeof(array1[0]);i++){ bool check1= check2= false; if(result.size() == 0 && array1[i] != array2[i]){ result.push_back(array1[i]); result.push_back(array2[i]); } else if(result.size() == 0 && array1[i] == array2[i]){ result.push_back(array1[i]); } else { for(int j=0; j<result.size(); j++){ if(array1[i] == result[j]) check1= true; } if(!check1) result.push_back(array1[i]); for(int j=0; j<result.size(); j++){ if(array2[i] == result[j]) check2= true; } if(!check2) result.push_back(array2[i]); } } for(vector<string>::iterator it= result.begin(); != result.end(); it++){ cout<<*it<<" "; } cout<<endl; return 0; }
Comments
Post a Comment