boost - 将一系列结构向量插入到结构成员类型的向量中

标签 boost vector struct c++03

是否可以将结构范围直接插入相同类型的向量(结构成员的相同类型)。

让我们有一个这样的结构和向量:

struct pnt {
  char _name;
  int _type;
  bool _aux;
  };

std::vector<pnt> pnts;
std::vector<int> pntType;

问题是如何使用 C++98 的单个标准行将一系列 pnts 插入 pntType:

void insert (iterator position, InputIterator first, InputIterator last);

甚至是 Boost 库。 因为我经常在代码的不同部分使用它,所以我试图避免在循环中这样做。最后一个选项是为此定义一个函数。

编辑:

我知道插入语法。我不能做的是如何从 pnts (每个成员只有 _type)插入 pntType

最佳答案

更新:有比我的第一个建议(见底部)更好的方法,因为我们已经在使用 Boost。 std::transform 和 std::insert_iterator 的问题是 v2 被多次调整大小,考虑到我们提前知道范围的宽度,这是一种浪费。使用 boost::transform_iterator 和 boost::bind,可以避免这样的问题:

#include <boost/bind.hpp>
#include <boost/iterator/transform_iterator.hpp>

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

struct A {
  int x;
};

int main() {
  A arr[] = {
    { 0 }, { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }
  };

  std::vector<A> v1(arr, arr + 6);
  std::vector<int> v2;

  v2.insert(v2.begin(),
            boost::make_transform_iterator(v1.begin() + 2, boost::bind(&A::x, _1)),
            boost::make_transform_iterator(v1.begin() + 4, boost::bind(&A::x, _1)));

  std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

旧建议:

boost::bind 与数据成员指针一起工作,因此使用 C++98 和 Boost,你可以在不改变你的结构的情况下做这样的事情:

#include <boost/bind.hpp>

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

struct A {
  int x;
};

int main() {
  A arr[] = {
    { 0 }, { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }
  };

  std::vector<A> v1(arr, arr + 6);
  std::vector<int> v2;

  // one-liner here:
  std::transform(v1.begin() + 2,
                 v1.begin() + 4,
                 std::insert_iterator<std::vector<int> >(v2, v2.begin()),
                 boost::bind(&A::x, _1));

  std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

关于boost - 将一系列结构向量插入到结构成员类型的向量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969327/

相关文章:

c++ - 从二进制文件 (C++) 读取结构的烦人错误

c++ - boost 编译错误 Mac OS X 10.7.4

c++ - 统一初始化以调用初始化程序列表以外的构造函数

reflection - 在方法调用中找到真正的调用者

c++ - 数据越大,内存分配错误

c++ - 为什么在 operator< 存在时定义 lt?

c - 指向结构体指针的指针

c++ - 使用容器解析为结构

c++ - Boost Asio延迟写入tcp套接字

c++ - 逻辑非运算符在 boost::spirit::qi 中不起作用