Home > database >  How to filter rows of matrix by column values?
How to filter rows of matrix by column values?

Time:12-22

How to get a subset matrix from matrix?

e.g. where in column 3, value = 4?

vector<vector<int>> items =
    {
        // uID, q*, p*, t
        {1,3,1,9866},
        {2,1,2,5258},
        {3,2,4,5788},
        {4,2,4,6536},
        {5,2,4,6534},
    };

Result:

results =
    {
        // uID, q*, p*, t
        {3,2,4,5788},
        {4,2,4,6536},
        {5,2,4,6534},
    };

CodePudding user response:

You could use std::copy_if:

#include <algorithm>  // std::copy_if
#include <iterator>   // std::back_inserter

    //...

    // the resulting vector:
    std::vector<std::vector<int>> results;

    // copy those inner vectors where column 3 == 4:
    std::copy_if(items.begin(), items.end(), std::back_inserter(results),
                 [](const std::vector<int>& inner){
                     return inner.size() >= 3 && inner[2] == 4;
                 });

Demo

CodePudding user response:

Another approach is simply to loop over items selecting rows where the 3rd element is 4 and use .push_back() to add that row to a new std::vector<std::vector<int>>, e.g.

#include <iostream>
#include <vector>

int main() {

  std::vector<std::vector<int>> items =
    {
        // uID, q*, p*, t
        {1,3,1,9866},
        {2,1,2,5258},
        {3,2,4,5788},
        {4,2,4,6536},
        {5,2,4,6534},
    },
    results{};
  
  for (const auto& row : items) {      /* loop over all rows of items */
    if (row[2] == 4)                   /* select rows where 3rd col == 4 */
      results.push_back(row);          /* add row to results */
  }
  
  for (const auto& row : results) {    /* output results */
    for (const auto& col : row)
      std::cout << " " << col;
    std::cout.put('\n');
  }
}

Example Use/Output

./bin/select_from_vv
 3 2 4 5788
 4 2 4 6536
 5 2 4 6534

See also Why is “using namespace std;” considered bad practice?

  •  Tags:  
  • c
  • Related