0

We have 1 vector of vectors:

vector<vector<int>> vectors;

vectors has n vector inside.Lets say it has 3 vectors

n1=[6,9,17,21]

n2=[2,4,6]

n3=[3,6,9,12]

How do iterate thorough vectors and compare those vectors(n1,n2,n3 in this case) to find common element(6)?

l0veisreal
  • 179
  • 5
  • 20
  • @Scheff if its easy can you give an example im new to programming thanks – l0veisreal Oct 20 '18 at 16:00
  • I could but I will not. ;-) This is no homework service. Show an attempt to turn my algorithm into C++ code. If you fail or feel lost edit your code into the question (or start a new one if this has been closed meanwhile). Then, you will surely get help. – Scheff's Cat Oct 20 '18 at 16:07
  • Btw. the link of @Max already provides the answer to your question. (And it seems that I didn't read it carefully enough. I didn't understand it correctly until I saw the answer in the link.) – Scheff's Cat Oct 20 '18 at 16:12
  • As I gave an algorithm for the wrong problem first, a new attempt: Copy first vector of `vectors` as pivot. Iterate through `vectors` beginning with the second (or the first to make it simpler). For each vector: erase each element from pivot which is not in the current vector. Checking whether a value is in a vector is simply comparing every element until one is equal (bail out with success) or end is reached (fail). Note: This naive approach will have terrible time complexity but it's a simple way to implement it. For your test sets, it will probably be not a problem. – Scheff's Cat Oct 20 '18 at 16:25
  • what if i combine vectors in 1 vector then check that vector for most repeated element – l0veisreal Oct 20 '18 at 16:29

1 Answers1

0

The code below shows how to iterate through a vector of vectors.

const size_t quantity_vectors(vectors.size());
for (size_t i = 0; i < quantity_vectors; ++i)
{
   const std::vector<int>& vector_a(vectors[i]);
   const std::vector<int>& other_vector(vectors[(i + 1) % quantity_vectors]);
   const size_t quantity_a_vector(vector_a.size());
   for (size_t j = 0; j < quantity_a_vector; ++j)
   {
      // do something
      // example:  std::find(other_vector.begin(), other_vector.end(), vector_a[j]);
   }
}

The expression vectors[i] returns a std::vector.
I'm using a reference to avoid making copies. The reference is const because I'm not changing anything inside the vectors.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154