将容器的内容替换为其他容器中的数据

Replace the content of container with data from another container

本文关键字:数据 其他 替换      更新时间:2023-10-16

代码的设计是这样的:

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_dataO(temp_data.size())效率高得多。如果您不关心作业后temp_data的内容,请使用它。

虽然正如Toby Speight在评论中正确指出的那样,移动分配很可能通过swap实现,但无论如何,它更具表现力:代码的读者不必猜测你为什么交换内容,以及temp_data如何在代码中进一步使用。

相关文章: