Akki
Akki

Reputation: 3

C++ exchanging a vector between 2 vector of vectors

I have 2 vectors of vector for a struct, say A.

If you consider them as matrix A, the number of rows in both matrix will be the same but each row has a different length, so it is not a perfect matrix.

Based on a computed metric, the row of one vector is copied to another.

For example:

#include <vector>
struct A {
  int a;
  int b;
};

std::vector<double> computeMetric(std::vector<std::vector<A>> v) {
  std::vector<double> temp(v.size(), 0);

  for (size_t i = 0; i < v.size(); i++) {
    for (size_t j = 0; j < v[i].size(); j++) {
      temp[i] += v[i][j].a / v[i][j].b;
    }
  }
  return temp;
}

int main() {
  std::vector<std::vector<A>> v1;
  std::vector<std::vector<A>> v2;

  std::vector<double> metricV1 =
      computeMetric(v1); // size() = V1.size() = v2.size()
  std::vector<double> metricV2 =
      computeMetric(v2); // size() = V1.size() = v2.size()

  for (size_t i = 0; i < metricV1.size(); i++) {
    if (metricV1[i] > metricV2[i])
      v1[i] = v2[i];
  }
  return 0;
}

but v1[i] = v2[i]; is not correct and so I used erase() and insert().

Will the results be what is expected and is this the more efficient way of doing it?

Upvotes: 0

Views: 118

Answers (1)

Mosa Abbas
Mosa Abbas

Reputation: 149

after researching there is a reference in c++ documentation you can find here

You can use std::vector::swap(). and it's the most efficient way of swapping two vectors here is an example of swapping

// CPP program to illustrate swapping  
// of two vectors using std::vector::swap() 

#include<bits/stdc++.h> 
using namespace std; 

int main() 
{ 
    vector<int> v1 = {1, 2, 3}; 
    vector<int> v2 = {4, 5, 6}; 

    // swapping the above two vectors 
    // using std::vector::swap 
    v1.swap(v2); 

    // print vector v1 
    cout<<"Vector v1 = "; 
    for(int i=0; i<3; i++) 
    { 
        cout<<v1[i]<<" "; 
    } 

    // print vector v2 
    cout<<"\nVector v2 = "; 
    for(int i=0; i<3; i++) 
    { 
        cout<<v2[i]<<" "; 
    } 

    return 0; 
} 

so using std::swap() is the most efficient way of exchanging a vector between 2 vector of vectors

Upvotes: 1

Related Questions