Need a help slicing 2D vector

Hello everyone,
I need a help slicing a 2D vector. I guess it is easy but since I am complete beginner I could nout achieve to sclice them. I have one 1D vector F=[1 2 1 2]
and one 2D vector like V={{3 6 7}{1 4 7}{ 4 6 8}{ 1 4 5}} . As you can realize , the size of F vector is equal to row number of V vector. What I need to do: Finding the same numbers in F and their indices and slice them from V vector and construct another vector: For example we have 1 in F , its indices 0 and 2 in F , so I need to slice row[0] and row[2] from V vector and I should construct another matrix like V1={{3 6 7}{4 6 8}. need to do same for 2 in F vector whose indices are 1 and 3 so I need to construct V2={1 4 7}{1 4 5}} .

Thank you so much for all your helps

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
using namespace std;

using matrix = vector<vector<int>>;

//======================================================================

void print( const matrix &M )
{
   for ( auto &row : M )
   {
      for ( auto e : row ) cout << e << '\t';
      cout << '\n';
   }
}

//======================================================================

matrix rowSlice( const matrix &original, const vector<int> &rowIndices )
{
   matrix result;
   for ( int i : rowIndices ) result.push_back( original[i] );
   return result;
}

//======================================================================

vector<int> getIndices( const vector<int> &F, int value )
{
   vector<int> result;
   for ( int i = 0; i < F.size(); i++ ) if ( F[i] == value ) result.push_back( i );
   return result;
}

//======================================================================

int main()
{
   matrix M = { { 3, 6, 7 }, { 1, 4, 7 }, { 4, 6, 8 }, { 1, 4, 5 } };
   vector<int> F = { 1, 2, 1, 2 };

   matrix M1 = rowSlice( M, getIndices( F, 1 ) );
   matrix M2 = rowSlice( M, getIndices( F, 2 ) );

   cout << "M1:\n";   print( M1 );   cout << "\n\n";
   cout << "M2:\n";   print( M2 );   cout << "\n\n";
}


M1:
3	6	7	
4	6	8	


M2:
1	4	7	
1	4	5




Use inbuilt function slice() in C++ STL to slice the given vector.
https://www.dmvnow.me/
Last edited on
Thank you so much @lastchance. I had achieved to find the indices but I had hard times with slicing task. Thank you so much
Thank you so much @Ethan69 as well for the info.
std::slice doesn't work on a vector, only on a valarray:
https://en.cppreference.com/w/cpp/numeric/valarray/slice

Eathan just wanted a nebulous reply so he could transform it into a spam post later.
Topic archived. No new replies allowed.