[英]C++ exchanging a vector between 2 vector of vectors
I have 2 vectors of vector for a struct, say A.对于一个结构,我有 2 个向量向量,比如 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.如果将它们视为矩阵 A,则两个矩阵中的行数将相同但每行的长度不同,因此它不是一个完美的矩阵。
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];
但是v1[i] = v2[i];
is not correct and so I used erase()
and insert()
.不正确,所以我使用了erase()
和insert()
。
Will the results be what is expected and is this the more efficient way of doing it?结果会是预期的结果吗?这是更有效的方法吗?
after researching there is a reference in c++ documentation you can find here在研究了 c++ 文档中有一个参考后,你可以在这里找到
You can use std::vector::swap().
您可以使用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所以使用std::swap()
是在 2 个向量向量之间交换向量的最有效方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.