使用来自联合数组的数据初始化std :: vector

时间:2012-09-12 15:11:29

标签: c++

我如何从结构数组中初始化std :: vector,其中struct包含不同类型的并集。换句话说,该数组用于存储特定类型的多个值,可以是int,char *等。

到目前为止,这是我的解决方案,但我正在寻找更好的方法:

转换函数如果存储vector<int>则返回int,如果存储vector<std::string>则返回char*

下面的Value类型是一个包含名为value的union的结构。下面的Container类指向这些值的缓冲区。

// union member getter
class Getter
{
public:

    void operator()(int8_t& i, const Value& value)
    {
        i = value.value.i;
    }

    void operator()(std::string& s, const Value& value)
    {
       s = std::string(value.value.s);
    }

    ...
};

template<class T>
std::vector<T> convert(Container* container)
{
    std::vector<T> c;
    c.reserve(container->nrOfValues);
    Getter g;
    for(int i=0;i<container->nrOfValues;i++)
    {
        T value;
        g(value, container->values[i]);
        c.push_back(value);
    }
    return c;
}

2 个答案:

答案 0 :(得分:1)

你的问题是union为每个值赋予了一个不同的名称,这导致需要一个将名称转换为类型的函数,例如Getter :: operator()返回一个类型并获取一个联合的命名成员

你无能为力。您可以在每个项目上保存变量声明和复制/字符串构造函数,但这就是它。

如果无法修改原始结构,可以使用默认值的长度集(必须传入)初始化向量,然后使用getter迭代:

vector<T> v(length, defaultValue);
typename vector<T>::iterator iter = vec.begin();
for(int index = 0; *iter != vec.end() && index < length; ++iter, ++index) {
  converter(*iter, array[index]);
}

请注意,这在迭代索引和迭代器时开始变得麻烦,并且在发生事故时验证两者仍然有效...

如果你可以修改原始结构:

class Ugly { // or struct, it doesn't matter
public:
  union {
    char* s;
    int i;
  } value;

  Ugly(char* s) {
    value.s = s;
  }

  Ugly (const int& i) {
    value.i = i;
  }

  operator std::string() const {
    return std::string(value.s);
  }

  operator int() const {
    return value.i;
  }
};

然后你的for循环变为:

for(int i=0;i<container->nrOfValues;i++)
{
    c.push_back(container->values[i]);
}

注意:您可以创建向量并将其作为参数传递给复制函数,因为它涉及在返回期间复制数据。

答案 1 :(得分:1)

如果你喜欢一些模板魔术,你可以采用稍微不同的方式:

// Source union to get data from
union U
{
  int i;
  char* s;
  double d;
};

// Conversion type template function (declared only)
template <class T> T convert(const U& i_u);

// Macro for template specializations definition
#define FIELD_CONV(SrcType, DestField)\
template <> SrcType convert(const U& i_u)\
{ auto p = &DestField; return i_u.*p; }

// Defining conversions: source type -> union field to get data from
FIELD_CONV(int, U::i)
FIELD_CONV(std::string, U::s)
FIELD_CONV(double, U::d)

// Get rid of macro that not needed any more - just for macro haters ;-)
#undef FIELD_CONV

// Usage
template<class T> std::vector<T> convert(Container* container)
{
   std::vector<T> c;
   c.reserve(container->nrOfValues);
   for(int i = 0; i < container->nrOfValues; ++i)
     c.push_back(convert<T>(container->values[i])); 
   return c;
} 

这种方法的优点 - 它简短,易于扩展。将新字段添加到union时,只需编写另一个FIELD_CONV()定义。

编译示例为here