使用向量作为索引实现对引导向量的访问 [英] Implementing access to vector of stucts using a vector as indices

查看:150
本文介绍了使用向量作为索引实现对引导向量的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些高级语言有这个功能,我试图在C ++中实现。我不知道是否有一个已经在这个地方有一个图书馆,但如果有,这将拯救我很多麻烦。无论如何,这里是我想要完成的:



让我们假设我有一个结构体的向量,有一个double和一个int作为成员,我有另一个向量的int,它表示我想保留的结构体向量中的元素的索引。

  typedef struct 
{
double x;
int y;
} s;

std :: vector< s> v;
std :: vector< int> inds;

有一种方法来实现访问结构中的元素使用索引的向量

  std :: vector< double> dResult = v [inds] .x; 
std :: vector< int> iResult = v [inds] .y;

以这种方式访问​​所有元素也是很好的:

  std :: vector< double> d = v.x;这些事情可能吗?

解决方案


  1. 您不能对 std :: vector 的现有定义使用该语法。

  2. 不能创建提供该语法的全局运算符过载函数,因为 operator []()只能作为成员函数重载。

  3. 您可以创建提供功能但不使用该语法的非成员函数。

 模板< typename T1,typename T2> 
std :: vector< T2> getElements(std :: vector< T1> const& vec,
std :: vector< int> const& indices,
T2(T1 :: * member))
{
std :: vector< T2> ret;
for(auto index:indices)
{
ret.push_back(vec [index]。* member);
}
return ret;
}

,然后将其用作:

  std :: vector< s> v; 
std :: vector< int> inds;
std :: vector< double> dResult = getElements(v,inds,& s :: x);


Some higher-level languages have this feature, and I'm attempting to implement in C++. I'm not sure if there's a library that already does this somewhere, but if there is, it would save me a lot of trouble. Anyway, here's what I'm trying to accomplish:

Let's say I have a vector of structs that have a double and an int as members, and that I have another vector of ints that represents the indices of the elements in the vector of structs that I want to keep.

typedef struct
{
double x;
int y;
}s;

std::vector<s> v;
std::vector<int> inds;

Is there a way to implement accessing the elements in the structure using the vector of indices in a manner similar to this, or has it been implemented elsewhere?

std::vector<double> dResult = v[inds].x;
std::vector<int> iResult = v[inds].y;

It would also be nice to be able to access all of the elements in this manner:

std::vector<double> d = v.x;

Are these things possible?

解决方案

  1. You cannot use that syntax with existing definitions of std::vector.
  2. You cannot create a global operator overload function that provides that syntax since operator[]() can be overloaded only as a member function.
  3. You can create a non-member function that provides the functionality but without using that syntax.

template <typename T1, typename T2>
std::vector<T2> getElements(std::vector<T1> const& vec,
                            std::vector<int> const& indices,
                            T2 (T1::*member))
{
   std::vector<T2> ret;
   for ( auto index : indices )
   {
      ret.push_back(vec[index].*member);
   }
   return ret;
}

and then use it as:

std::vector<s> v;
std::vector<int> inds;
std::vector<double> dResult = getElements(v, inds, &s::x);

这篇关于使用向量作为索引实现对引导向量的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆