使用std :: transform最终向量保持为空 [英] using std::transform the final vector remains empty

查看:56
本文介绍了使用std :: transform最终向量保持为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不经常使用std :: transform,但是我发现它非常有用,并且我开始用这种算法替换一些for循环。

I am not using std::transform often, however I found it very useful and I am starting replacing some for loops with this algorithm.

这里有什么问题?我想保留向量vec中所有代码> 100的元素。我希望有一个带有3个元素的新std :: vector:133、144和155。但是在算法之后,大小为0。 ?

What is wrong here? I want to keep all the elements of the vector vec that have code > 100. I would expect to have a new std::vector with 3 elements: 133, 144 and 155. But after the algorithm the size is 0. What is wrong?

 TEST_CASE("testing trasf1", "[tras1]") {

    std::vector<Test2> vec {
            {1,1},
            {3,3},
            {11,11},
            {12,12},
            {133,133},
            {19,19},
            {21,21},
            {22,22},
            {23,23},
            {144,144},
            {155,155}

    };

    std::vector<uint32_t> final_v {};
    final_v.reserve(vec.size());

    transform(begin(vec), end(vec), begin(final_v), [] (const Test2& elem) {
        if ( elem.getCode() > 100)
            return elem.getCode();
    });

    //REQUIRE(final.size() == 3);

    cout << final_v.size() << endl;

    for (const auto i : final_v) {
        cout << i << endl;
    }

}


推荐答案

transform 不会在输出序列中插入元素,它只是写入 * iter 并递增

transform doesn't insert elements into the output sequence, it just writes to the *iter and increments the iterator.

如果要插入到序列中,请使用 std :: back_inserter(final)作为输出迭代器。

If you want to insert to the sequence, use std::back_inserter(final) as the output iterator.

或者,先调用 final.resize(vec.size())设置输出矢量到正确的大小。请注意,这会将向量元素初始化为零,因此对于大向量,将产生明显的时间开销。

Alternatively, call final.resize(vec.size()) first, to set the output vector to the correct size. Note that this will intialize the vector elements to zero, so for large vectors will incur a noticeable time overhead.

这篇关于使用std :: transform最终向量保持为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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