简体   繁体   English

C ++转换向量 <pair<double,double> &gt;翻倍*,翻倍*?

[英]c++ convert vector<pair<double,double>> to double*, double*?

Is there a way to get the contiguous memory of the ".first" and ".second" of vector<pair<double,double>> ? 有没有办法获取vector<pair<double,double>> “ .first”和“ .second”的连续内存? What I mean is: 我的意思是:

void func(int N, double* x, double* y)
{
    for (int i = 0; i < N; ++i)
        //do something to x[i] and y[i]
}

For the above function I have a vector<pair<double,double>> point rather than vector<double> x, y . 对于上述函数,我有一个vector<pair<double,double>> point而不是vector<double> x, y I'm guessing this is not possible. 我猜这是不可能的。 If I had a vector x,y then I could do x.data() and y.data() of course. 如果我有向量x,y,那么我当然可以做x.data()和y.data()。

The memory layouts of std::vector<std::pair<double, double>> xy and std::vector<double> x,y are different. std::vector<std::pair<double, double>> xystd::vector<double> x,y的内存布局不同。 If func is part of a third-party library you can not change, you are bound to 如果func是第三方库的一部分,您不能更改,那么您必然

a) call func a couple of times with N=1 or (quick an dirty) 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) convert xy to x and y b)将xy转换为xy

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) simply change the defintions of xy to x and y . c)只需将xy的定义更改为xy

If you can change func , I propose to refactor such that you can call the inner loop and rewrite it for iterators (or ranges). 如果可以更改func ,我建议进行重构,以便您可以调用内部循环并将其重写为迭代器(或范围)。 That way you could use it with projections on std::pair s. 这样,您可以将其与std::pair的投影一起使用。

Here is the full source code. 这是完整的源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM