简体   繁体   中英

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
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++
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.

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):

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)

Following Viktor's answer , you could use std::set_difference to remove elements (but loop is much cleaner alternative)

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. Profiling would be required to truly determine which one is faster. Loop is certainly more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM