将容器的内容替换为其他容器中的数据
Replace the content of container with data from another container
代码的设计是这样的:
std::list<std::string> core_data;
...<filling this list up during the application workflow
....
while (<some condition>) {
std::list<std::string> temp_data;
//... <some logic to build temp_data
// ... based on the elements from core_data
// ...
// replace core_data with temp_data for next iteration
// in this point core_data is already empty
core_data = temp_data;
}
用temp_data分配core_data最有效的方法是什么?
这种方式正确吗?更有效?
core_data = std::move(temp_data);
说出core_data.swap(temp_data)
。
core_data = std::move(temp_data);
(O(1)
)比core_data = temp_data
(O(temp_data.size()
)效率高得多。如果您不关心作业后temp_data
的内容,请使用它。
虽然正如Toby Speight在评论中正确指出的那样,移动分配很可能通过swap
实现,但无论如何,它更具表现力:代码的读者不必猜测你为什么交换内容,以及temp_data
如何在代码中进一步使用。
相关文章:
- C++ - 忽略并从其他文件获取数据
- 如何通过ROS将realsense数据传输到其他设备
- 使来自线程的数据流对所有其他线程都可读
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 哪些 C++ 数据类型是 Metal 和所有其他 C++ 平台共有的
- 只知道运行时的数据类型.如何将数据详细信息隐藏到使用它们的其他类
- 连接UDP套接字,但仍然接收来自其他源的数据报
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- 从 Windows 中的其他应用程序 GUI 中提取数据
- QCombobox,字符串旁边有项目的其他数据
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- GLSL 计算着色器 使用查找表设置缓冲区会导致不写入任何数据,与其他数据设置相同的缓冲区有效
- 如何将模运算符与其他数据类型一起使用
- 将指针与其他数据相关联
- 如何通过将JSON数据修改为RapidJson通过将其修改为其他模式
- 当并行线程访问同一数据结构的其他成员时,正确的方法可以在Visual Studio上的OpenMP上并行循环
- 将多种数据类型写入文件时的其他行和额外的数组元素
- 作为其他类成员的类:创建一个接受所有数据的构造函数
- 如何有效地将底层数据从 std::string 移动到其他类型的变量?
- 类更改数据其他类的成员