Home c++ vector of classes - call

vector of classes – call

Author

Date

Category

There is a class, there is a vector of vectors of this class. How to refer to an element of a class through a vector of vectors?

class primer {
public:
string date;
string hello;
};
int main ();
primer p [2];
vector & lt; vector & lt; primer & gt; & gt; p1;
vector & lt; primer & gt; p2;
string q = "qwerty";
p [0] .date = "22.01";
p [0] .hello = "asd";
p2.push_back (p);
p1.push_back (p2);
p [1] .date = "22.19";
p [1] .hello = "qwerty";
p2.push_back (p);
p1.push_back (p2);

And after the call, it is necessary to find in the vector p1 a string that is equal to q and display all the elements of this class to which the found string belongs


Answer 1

For to compile , you need to do this:

int main ()
{
  primer p [2];
  vector & lt; vector & lt; primer & gt; & gt; p1;
  vector & lt; primer & gt; p2;
  string q = "qwerty";
  p [0] .date = "22.01";
  p [0] .hello = "asd";
  p2.push_back (p [0]);
  p1.push_back (p2);
  p [1] .date = "22.19";
  p [1] .hello = "qwerty";
  p2.push_back (p [1]);
  p1.push_back (p2);
}

But if this is what you want – figure it out for yourself 🙂 Here you have the first vector in the vector – from one element, the second – from two …

Then just use a loop like

for (const auto & amp; p2: p1)
{
   // Look for a string in p2, if there is - print p2
   // Type through all the lines in p2
   // for (auto x: p2)
   // if (x.date == q) // if there is a line
   // for (auto y: p2) cout & lt; & lt; y.date; // print the whole p2
   // (Sketch on the knee, not for compilation :))
}

Or, even compiled 🙂 –

int main ()
{
  primer p [2];
  vector & lt; vector & lt; primer & gt; & gt; p1;
  vector & lt; primer & gt; p2;
  string q = "qwerty";
  p [0] .date = "22.01";
  p [0] .hello = "asd";
  p2.push_back (p [0]);
  p1.push_back (p2);
  p [1] .date = "22.19";
  p [1] .hello = "qwerty";
  p2.push_back (p [1]);
  p1.push_back (p2);
  for (const auto & amp; p: p1)
  {
    for (const auto & amp; r: p)
      if (r.hello == q)
        for (const auto & amp; v: p)
          cout & lt; & lt; v.date & lt; & lt; "" & lt; & lt; v.hello & lt; & lt; "\ n";
  }
}

True, it’s prettier all the same through the algorithms of the standard library …

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions