简体   繁体   English

将 int 数组转换为 std::vector<int*>

[英]Convert int array to std::vector<int*>

I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.我正在尝试将整数 C 样式数组“转换”为std::vector<int*>而不使用for循环,或者更确切地说是在向量中插入所有数组项的指针。

I'm currently implementing this by doing the follow:我目前正在通过执行以下操作来实现这一点:

for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}

Is it possible to implement this by using std::vector::insert() and std::being/end ?是否可以通过使用std::vector::insert()std::being/end

std::transform is a useful algorithm in <algorithm> for copying values between containers that aren't implicitly compatible but for which you can provide a transformation function. std::transform<algorithm>一种有用算法,用于在不隐式兼容但您可以为其提供转换函数的容器之间复制值。

Here is an example of how you could populate a std::vector<int*> from a std::array<int, N>这是一个如何从std::array<int, N>填充std::vector<int*>的示例

int values[5] = { 1,2,3,4,5 };
std::vector<int*> v1;

std::transform(
    std::begin(values), std::end(values),   // Copy from
    std::back_inserter(v1),                 // Copy to
    [](auto& i) {                           // Transformation function
        return &i;
    });

Edit : Changed std::array<int, 5> to int[5] to account for edits in the question.编辑:将std::array<int, 5>更改为int[5]以说明问题中的编辑。

The code below is rather fancy way to do what you want, but it is generic and it doesn't use for loop - it just passes pointers of array's elements to vector constructor:下面的代码是做你想做的事情的相当奇特的方式,但它是通用的,它不使用for循环 - 它只是将数组元素的指针传递给向量构造函数:

template<class T, size_t ... Ints, size_t N>
std::vector<T*> makePtrsHelper(std::array<T,N>& arr, std::index_sequence<Ints...>) {
       return std::vector<T*>{ & std::get<Ints>(arr)... }; 
       // vector ctor taking pointers to array's elements
}

template<class T, size_t N>
std::vector<T*> makePtrs(std::array<T,N>& array) {
    return makePtrsHelper(array, std::make_index_sequence<N>{});
}

int main(){
    std::array<int,5> ar{1,2,3,4,5};
    std::vector<int*> v = makePtrs(ar);

Live demo现场演示

Note : as pointed out in comments my below answer is wrongly related to vector<int> not vector<int*> which was asked for in question.注意:正如评论中指出的,我下面的答案错误地与vector<int>而不是vector<int*> ,这是有问题的。


Solution with std::copy and C-style array:使用std::copy和 C 样式数组的解决方案:

int ar[] = {1,2,3,4,3,2,1};
std::vector<int> vec;
std::copy(ar, ar+sizeof(ar)/sizeof(ar[0]), back_inserter(vec));

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

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