mardi 23 novembre 2021

subset std::map into std::vector

im trying to subset a std::map<string,string> into a vector of maps, each with predefined length + rest. Im trying to follow the solution found in this Can a std::map be efficiently split into two std::maps at an iterator? The problem here: I don't want to split the map into two parts, but into n parts each of equal size + rest. That's how im trying to achieve this (not compiling because of a nullptr):

#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <map>

int main(){
using namespace std::string_literals;

    auto code = std::map<std::string, std::string>{
        {"Red"s, "Red"s},
        {"Blue"s, "Blue"s},
        {"Green"s, "Green"s},
        {"Fuchsia"s, "Fuchsia"s},
        {"Mauve"s, "Mauve"s},
        { "Gamboge"s, "Gamboge"s },
        {"Vermillion"s, "Vermillion"s}
    };
    
    std::vector<std::map<std::string,std::string>> subsetCode;
    auto it = code.begin();
    auto bt = code.begin();
    for (size_t i = 0; i < code.size(); i += 2)
        {
            auto last = std::min(code.size(), i + 2);
            
            std::advance(it, last);
            std::advance(bt, last-2);
            subsetCode.push_back(std::map{
                std::make_move_iterator(bt),
                std::make_move_iterator(it)});
        }
    
    for (int i = 0; i < subsetCode.size(); i++) {
        for (auto [key, value]: subsetCode[i]){
            std::cout << key << ":" << value << " ";
        }
        std::cout << " " << std::endl;
    }

    return 1;

I think i am stuck with moving the iterator for the lower bound. Thank you for your help!

Aucun commentaire:

Enregistrer un commentaire