有没有办法获得vector<pair<double,double>>的".first“和".second”的连续记忆?我的意思是:
void func(int N, double* x, double* y)
{
for (int i = 0; i < N; ++i)
//do something to x[i] and y[i]
}对于上面的函数,我使用的是vector<pair<double,double>> point而不是vector<double> x, y。我猜这不可能。如果我有一个向量x,y,那么我当然可以做x.data()和y.data()。
发布于 2017-02-17 19:34:45
std::vector<std::pair<double, double>> xy和std::vector<double> x,y的内存布局是不同的。如果func是您不能更改的第三方库的一部分,则您将绑定到
a)使用N=1或(快速和脏)调用func几次
auto xy = std::vector<std::pair<double, double>> {
{0,0}, {42,0}, {0, 42}, {42, 42}
};
for (auto& [x,y] : xy) { // or for (auto& p : xy) func(1, p.first, p.second)
func(1, &x, &y);
}b)将xy转换为x和y
template <typename T, typename S>
auto convert(const std::vector<std::pair<T,S>>& xy)
{
auto xs = std::vector<T>{};
auto ys = std::vector<S>{};
xs.reserve(xy.size());
ys.reserve(xy.size());
for (auto& [x,y] : xy) {
xs.push_back(x);
ys.push_back(y);
}
return std::make_pair(xs, ys);
}
int main()
{
auto xy = std::vector<std::pair<double, double>> {
{0,0}, {42,0}, {0, 42}, {42, 42}
};
auto [x, y] = convert(xy);
func(xy.size(), x.data(), y.data());
}c)只需将xy的定义更改为x和y。
如果您可以更改func,我建议进行重构,这样您就可以调用内部循环并为迭代器(或范围)重写它。这样你就可以在std::pairs上使用它进行投影了。
https://stackoverflow.com/questions/42296528
复制相似问题