简体   繁体   中英

C++ vector of pairs initialization - compilation error

I would like to initalize a vector of pairs with some hard-coded values, I tried using different solutions but I keep getting compilation error. My code looks like this:

std::vector<std::pair<cv::HOGDescriptor, std::ifstream> > hogs_files = {
    std::make_pair(hog, file),
    std::make_pair(hog2, file2),
    std::make_pair(hog3, file3),
    std::make_pair(hog4, file4),
    std::make_pair(hog5, file5),
    std::make_pair(hog6, file6),
    std::make_pair(hog7, file7),
    std::make_pair(hog8, file8)
};

and the error I've got is:

Error   C2440   '<function-style-cast>': cannot convert from   'initializer list' to '_Mypair'

Thank you for answers.

The general approach to initialize the vector of pair s is OK but the problem is that std::ifstream is not copy-constructible. Hence, you won't be able to use

std::vector<std::pair<cv::HOGDescriptor, std::ifstream> > hogs_files = {
    std::make_pair(hog, file),
    ...
};

However, you should be able to use std::ifstream* in the pair :

std::vector<std::pair<cv::HOGDescriptor, std::ifstream*> > hogs_files = {
    std::make_pair(hog, &file),
    ...
};

The error is because fstreams are not copy-constructible.

I would suggest you move your ifstreams to the vector of pairs; more clarity and control.

std::vector<std::pair<cv::HOGDescriptor, std::ifstream> > hogs_files = {
        std::make_pair(hog, std::move(file)),
        std::make_pair(hog2, std::move(file2)),
        std::make_pair(hog3, std::move(file3)),
        std::make_pair(hog4, std::move(file4)),
        std::make_pair(hog5, std::move(file5)),
        std::make_pair(hog6, std::move(file6)),
        std::make_pair(hog7, std::move(file7)),
        std::make_pair(hog8, std::move(file8))
    };

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