Gynteniuxas
Gynteniuxas

Reputation: 7093

Create 3rd vector while looping through 2 others

I'm totally newbie in C++ and I need to solve a problem with vectors. What I need is to merge two existing vectors and create third one. While I saw several answers, the difference here is I need vector #3 (values3) to contain not all values, but only those which are in both vectors #1 (values1) and #2 (values2). So, if integer 2 is in vector 1 but is not in vector 2, this number does not fit me. I should use a function provided below. Commented lines are which I don't know what to write in. Other lines are working.

void CommonValues(vector<MainClass> & values1, vector<MainClass> & values2, vector<MainClass> & values3)
{
    MainClass Class;
    string pav;
    int kiek;
    vector<MainClass>::iterator iter3; // ?
    for (vector<MainClass>::iterator iter1 = values1.begin(); iter1 != values1.end(); iter1++)
    {
        for (vector<MainClass>::iterator iter2 = values2.begin(); iter2 != values2.end(); iter2++)
        {
            if (iter1 == iter2)
            {
                pav = iter2->TakePav();
                iter3->TakePav(pav); // ?
                kiek = iter1->TakeKiek() + iter2->TakeKiek();
                iter3->TakeKie(kiek); // ?
                iter3++; // ?
            }
        }
    }
}

Upvotes: 0

Views: 49

Answers (1)

swang
swang

Reputation: 5249

You can sort values1 and values2, then use std::intersection: http://en.cppreference.com/w/cpp/algorithm/set_intersection

Your code at the moment won't work, among other problems, you are comparing iterator from vector 1 with iterator from vector 2, which doesn't make any sense. If you want to do it by looping, you should iterate through one vector and check if the value, for example *iter1, is in the 2nd vector.

Upvotes: 2

Related Questions