Home > other >  How to transform different containers with std library?
How to transform different containers with std library?

Time:06-06

Does it exist a way to transform containters of different types using std functions?

QSet<QString> res;
QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();

for(const auto& interface : allInterfaces){
    res.insert(interface.name());
}

CodePudding user response:

std::transform can accept different containers. You can see it in the function signature:

template< class InputIt,
      class OutputIt,
      class UnaryOperation >
OutputIt transform( InputIt first1,
                    InputIt last1,
                    OutputIt d_first,
                    UnaryOperation unary_op );

As you can see there are two template arguments InputIt and OutputIt, so it means they can be different.

Here's an example using std containers:

#include <iostream>
#include <vector>
#include <set>

int main()
{
    std::set<int> set = {0, 1, 2, 3 };
    std::vector<bool> vec(set.size());
    
    std::transform(set.begin(), set.end(), vec.begin(), [](int v){ return v % 2 == 0; });
    
    for(auto&& e : vec){
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

Live Example

With Qt containers should be something like (I can't verify though)

QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
QSet<QString> res(allInterfaces.size());

std::transform(allInterfaces.begin(), allInterfaces.end(), res.begin(), [](const QNetworkInterface& interface){
   return interface.name();
});
  •  Tags:  
  • c qt
  • Related