c++ - sort 2d vector based on another 2d vector -


So I have two 2D vectors, where the first row of vector 1 has normal values ​​and in the second column of vector 2 Common values ​​are. I want to sort the rows in vector 2 according to the values ​​in the first row of vector 2. What is the best way to do this?

This is what I have so far, although I wonder if there is any way to do better with such algorithms:

  (unsigned int I = 1; i & lt; vec2.size (); i ++) if (vec2 [i] [1]! = Vec1 [0] [i]) swap (vec2 [i], vec2 [i + 1] ]);    

A simple solution can be:

  Std :: vector & lt; Std :: vector & lt; Integer & gt; & Gt; V1 = {{3, 6, 4}, {1, 1, 1}, {1, 1, 1}}; Std :: vector & lt; Std :: vector & lt; Integer & gt; & Gt; V2 = {{1, 4, 1}, {1, 6, 1}, {1, 3, 1}}; Const std :: vector & lt; Int & gt; & Amp; Serial = V1 [0]; Std :: sort (v2.begin (), v2.end (), [& amp; order] (const std :: vector & lt; int & gt; & amp; r1, const std :: vector & lt; int & Gt; & amp; r2) {auto it1 = std :: find (order.begin (), order.end (), r1 [1]); auto it2 = std :: find (order.begin (), order .end (), r2 [1]); return (it1 - it2) & lt; 0;});   

However, this solution has a very high cost, O (n ^ 2 log n). It can be a problem depending on the size of the vector.

Another way would be to use an intermediate vector in the form of an indirection:

  std :: vector & lt; Integer & gt; Idxs (order.size ()); (Std :: size_t i = 0; i & lt; order.size (); i ++) idxus [i] = std :: find (order.begin (), order.end (), v2 [i] [ 1] for) - order.begin (); // After calculating the Intermediate vector, you can use v2 in this way: v2 [idxs [i]] [j]   

In this solution, O (N ^ 2) At the cost of cost, every time you reach v2 , then in some upper part.

Finally, you can try to come up with a custom sort solution. Even so, I believe it is not possible to solve this problem with this small price compared to O (N ^ 2).

Comments

Popular posts from this blog

Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

java - How not to audit a join table and related entities using Hibernate Envers? -

mongodb - CakePHP paginator ignoring order, but only for certain values -