【发布时间】:2021-07-02 14:58:13
【问题描述】:
这是我经常使用的那种代码:
struct MyData
{
public:
double a;
double b;
};
std::vector<double> complexFunction(const std::vector<double>& vIn)
{
std::vector<double> vOut;
// complex calculations on the vector vIn to make vOut
return vOut;
}
int main(int argc, char **argv)
{
std::vector<MyData> myVector;
// Fill myVector...
std::vector<double> vIn_a;
vIn_a.resize(myVector.size());
std::vector<double> vIn_b;
vIn_b.resize(myVector.size());
// I would like to avoid that
for(size_t i=0; i < myVector.size(); ++i)
{
vIn_a[i] = myVector[i].a;
vIn_b[i] = myVector[i].b;
}
// Now I can use complexFunction
std::vector<double> vOut_a = complexFunction(vIn_a);
std::vector<double> vOut_b = complexFunction(vIn_b);
// A bad alternative solution...
std::vector<double> vOut_a = complexFunction_specialForMyData_a(myVector);
std::vector<double> vOut_b = complexFunction_specialForMyData_b(myVector);
}
在使用complexFunction() 函数之前,有没有一种优雅的方法可以避免将vector 的内容复制到另一个vector 中?
我看到的另一种选择是为数据 MyData::a 和 MyData::b 创建两个临时函数,但这迫使我复制 complexFunction() 的代码。
C++11 中有哪些好的实践?
【问题讨论】:
-
我无法清楚理解您的意思,但如果您询问有关复制矢量的问题,this 可以帮助您
标签: c++ vector reusability