[英]How to convert "Set functions" such as removeAll and addAll from Java to C++? Can it be done using erase or insert?
I've been trying to convert a Java code to C++ and I stumbled upon this part of a code which repeats a couple of times.我一直在尝试将 Java 代码转换为 C++,我偶然发现了重复几次的代码的这一部分。
//JAVA
TreeSet<String> currentState = new TreeSet<String>();
TreeSet<String> allTransitions = new TreeSet<String>();
.
.
.
currentState.addAll(allTransitions);
.
.
.
currentState.removeAll(allTransitions);
I tried to achieve the same in C++ by typing the following code:我试图通过键入以下代码在 C++ 中实现相同的目标:
//C++
set<string> currentState;
set<string> allTransitions;
.
.
.
currentState.insert(allTransitions);
.
.
.
currentState.erase(allTransitions);
When I try compiling this code I get a lot of errors so I'm wondering is it even possible to replicate the same functions from Java to C++ easily or is there another way to add sets to eachother and remove them.当我尝试编译这段代码时,我遇到了很多错误,所以我想知道是否可以轻松地将相同的函数从 Java 复制到 C++,或者是否有另一种方法可以相互添加集合并删除它们。
Thanks in advance!提前致谢!
The first one need the begin and end iterator like this:第一个需要像这样的开始和结束迭代器:
currentState.insert(allTransitions.begin(), allTransitions.end());
The second is most easily performed using a for loop if operating on std::set
(which you can turn into a function):如果在std::set
(您可以将其转换为函数),则使用 for 循环最容易执行第二个:
for(const auto& t: allTransitions)
currentState.erase(t);
If you where to operate on a sorted std::vector/deque/list
etc you could have utilized the set functions for the second operation ( std::set_difference/set_intersection
etc)如果您在哪里对排序的std::vector/deque/list
等进行操作,您可以将 set 函数用于第二个操作( std::set_difference/set_intersection
等)
Following Viktor's answer , you could use std::set_difference
to remove elements (but loop is much cleaner alternative)按照 Viktor 的回答,您可以使用std::set_difference
删除元素(但循环是更干净的替代方案)
std::set<std::string> tempCurrentState;
std::set_difference(currentState.begin(), currentState.end(),
allTransitions.begin(), allTransitions.end(),
std::inserter(tempCurrentState, tempCurrentState.end()));
currentState = tempCurrentState;
It might or mignt not be slightly faster ( O(n + k)
time complexity rather than O(n*log(k))
), but there's additional copy.它可能会或不会稍微快一点( O(n + k)
时间复杂度而不是O(n*log(k))
),但是还有额外的副本。 Profiling would be required to truly determine which one is faster.需要进行分析才能真正确定哪个更快。 Loop is certainly more readable.循环当然更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.