为什么使用std :: transform会导致exc_bad_access [英] Why does this use of std::transform cause exc_bad_access

查看:69
本文介绍了为什么使用std :: transform会导致exc_bad_access的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在cpp应用程序中大概有此代码:

I have this code (roughly) in a cpp app:

QList<Foo> rawAssets = getlist();
QVector<std::pair<QString, QString>> assets;
std::transform(rawAssets.begin(), rawAssets.end(), assets.begin(), makePair);

当我再次使用资产时,这会导致 exc_bad_access 抛出.

That causes exc_bad_access to throw when I use assets again.

但是,如果我将 assets.begin()更改为 std :: back_inserter(assets),那么它将按预期工作.

However, if I change assets.begin() to std::back_inserter(assets) then it works as I expect.

我找到了 std :: transform 的教程,展示了两种用法.为什么我的情况不对?

I found tutorials for std::transform showing both kinds of usage. Why is it wrong in my case?

推荐答案

由于您刚刚声明了 QVector< std :: pair< QString,QString>>资产;因此它是 empty. assets.begin()等于 assets.end(),并指向空向量的末端

Since you've just declared QVector<std::pair<QString, QString>> assets; it's empty. assets.begin() is therefore equal to assets.end(), and points past-the-end of the empty vector.

std :: transform 的第三个参数是一个迭代器,通过该迭代器, transform 写入转换结果(并在转换后将其递增每次写).

The third parameter of std::transform is an iterator through which transform will write the results of the transformation (and increment it after each write).

当您传入 assets.begin()时, transform 将通过该过去的迭代器进行写入,从而导致越界写入.大致与 char x [3]相同;x [4] ='a';

When you pass in assets.begin(), transform will write through this past-the-end iterator, resulting in an out-of-bounds write. It's roughly the same as doing char x[3]; x[4] = 'a';

当您传入 std :: back_inserter(assets)时,您将创建一个特殊的迭代器,以使通过它进行的写入实际上将 insert 写入的元素插入 assets .一切都很好.

When you pass in std::back_inserter(assets), you create a special iterator such that writing through it actually inserts the written element into assets. So all is well.

如果资产已经足够大,并且您想覆盖其中的元素,则可以使用第一种形式.当您要使用转换结果扩展 资产时,使用第二种形式.

The first form could be used if assets was already of sufficient size, and you wanted to overwrite the elements in it. The second form is used when you want to extend assets with the results of the transformation.

这篇关于为什么使用std :: transform会导致exc_bad_access的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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