Search code examples
c++stringvectorconcatenation

I need an algorithm to concatenate 2 vectors and also update the vector in cases of common element in C++ (not specific to C++11)


I have 2 vectors say vector of string/char.

vector<string> dest having elements {"Demo01","Demo02","Demo03"}

vector<string> src having elements {"Demo03","Demo07","Demo08"}

I want to copy all the elements from src to dest such that if dest vector already has an element present in src vector, replace that element in the dest vector with string "Demo03Duplicate" If no common elements found, just copy it in the dest vector.(there can be more than one common element)

End result:

vector<string> dest having elements {"Demo01","Demo02","Demo03Duplicate","Demo07","Demo08"}


Solution

  • The most simple approach would be to just check for every element in src vector, if an duplicate exists in dest vector or not. If it exists just append Duplicate to it, else you can just push back the element as a new element in dest vector.

    The follow code would do the job -

    #include <iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    
    int main() {
        vector<string>src = {"Demo01","Demo02","Demo03"};
        vector<string>dest = {"Demo03","Demo07","Demo08"};
        //loop for every element in src, check if exists in dest 
        for(int i=0;i<src.size();i++){
            bool flg=true;  
            for(int j=0;j<dest.size();j++){
                //if duplicate found, append "duplicate" and set flg to false so we don't push_back later on
                if(src[i]==dest[j]){
                    dest[j] += "Duplicate";
                    flg = false;
                    break;
                }
            }
            // if no duplicates, then insert from src to dest.
            if(flg)
                dest.push_back(src[i]);
    
        }
        sort(dest.begin(),dest.end());
        for(auto el:dest)cout<<el<<" ";
        return 0;
    }
    

    That would be the brute force approach. Maybe there exists some better approach than this, but this approach would do the job as well.