gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:30:55 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com