有人可以帮助我理解此代码吗?transient()
和persistent()
在这里做什么?
引用:
CppCon 2017:Juan Pedro Bolivar Puente,“后现代不变数据结构”
时间戳:
19:03
vector<int> myitoa(vector<int> v, int first, int last)
{
auto t = v.transient();
for (auto i = first; i < last; ++i)
t.push_back(i);
return t.persistent();
}
See the video here而且,当我编译它时,我得到一个错误:
'class std::vector' has no member named 'transient'
需要任何特定的头文件吗?
最佳答案
在这种情况下,vector
不是std::vector
,它没有transient()
或persistent()
方法,因为编译器处于错误状态。正如Juan在18:06所说的,它实际上是一个immer::vector
:
So, I'm using the
immer
namespace everywhere here. Nothing isstd
vector. This is an immutable vector ...
如果您仔细地听视频,Juan会解释
transient()
和persistent()
实际在做什么,以及为什么(19:00-25:58)。简而言之,
vector
是不可变的,无法修改其内容,因此transient()
构成了vector
的copy + write View 。当循环修改 transient 时,将创建vector
数据的新副本,循环可以根据需要自由修改。然后persistent()
根据 transient 数据创建一个新的不变vector
。有关Transient Data Structures的更多详细信息,请参见:
Transient data structures are always created from an existing persistent ... data structure...
You obtain a transient 'copy' of a data structure by calling
transient
. This creates a new transient data structure that is a copy of the source, and has the same performance characteristics. In fact, it mostly is the source data structure, and highlights the first feature of transients - creating one is O(1). It shares structure with its source, just as persistent copies share structure.The second feature of transients is that creating one does not modify the source, and the source cannot be modified via use of the transient. Your source data is immutable and persistent as always.
...
When you are finished building up your results, you can create a persistent data structure by calling
persistent!
on the transient. This operation is also O(1). Subsequent to callingpersistent!
, the transient should not be used, and all operations will throw exceptions. This will be true also for any aliases you might have created.
关于c++ - C++中的 vector 持久性和 transient ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64812534/