String vectors concatenation

I have a series of row vectors, each of which contains dates. As a simple example, a vector A of size 2 may contain:

A[0] = "01-Jul-2010"; 
A[1] = "03-Jul-2010";

while the second vector B of size 3 may contain:

B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010"; 
B[2] = "04-Jul-2010";  

I would like to create a vector C that contains the "union" of the element in A and B:

C[0] = "01-Jul-2010";
C[1] = "02-Jul-2010";
C[2] = "03-Jul-2010";
C[3] = "04-Jul-2010"; 

When combining A and B, I don't want any duplicate dates, so each C element must be unique. Is there a built-in / stl function (or Boost library) that I can name will do this?

Thank!

+3
source share
4 answers

If set is not applicable, std :: unique is also possible:

   std::vector<std::string> A;
   std::vector<std::string> B;
   std::vector<std::string> C;

   A.resize (2u);
   B.resize (3u);

   A[0] = "01-Jul-2010";  
   A[1] = "03-Jul-2010"; 

   B[0] = "02-Jul-2010"; 
   B[1] = "03-Jul-2010";  
   B[2] = "04-Jul-2010";   

   C.reserve (5u);

   std::copy (
      A.begin (),
      A.end (),
      std::back_inserter (C)
      );

   std::copy (
      B.begin (),
      B.end (),
      std::back_inserter (C)
      );

   // std::unique requires sorted vector
   std::sort (C.begin(), C.end());
   C.erase (
      std::unique (C.begin(), C.end()),
      C.end ()
      );
0
source

STL a set_union function STL, () . , A B ,

#include <algorithm>
#include <iterator>
#include <vector>
#include <string>

...

std::vector<std::string> C;
std::set_union(A.begin(), A.end(), B.begin(), B.end(), std::back_inserter(C));

A B , / , .

bool is_earlier(const std::string& first_date, const std::string& second_date) {
   // return whether first_date is earlier than second_date.
}

...

std::set_union(A.begin(), A.end(), B.begin(), B.end(),
               std::back_inserter(C), is_earlier);
+5

( ) () . , , , , .

std::unique, std::remove_if std::set_union ( , ).

+1

, STL. , .

+1

Source: https://habr.com/ru/post/1762708/


All Articles