mercredi 2 octobre 2019

check if a vector contains a substring of another vector

I have file names and I need to check if these files end with any extension of the vector extensions; I would like to use some of the algorithms that are in the library instead of how I have done it, is there any way?

#include <iostream>
#include <algorithm>
#include <vector>

std::string tail(const std::string &st, const size_t len)
{
    if (len >= st.size())
        return st;
    return st.substr(st.size() - len);
}

std::vector<std::string> filtered_files(const std::vector<std::string>& files, const std::vector<std::string>& extensions) {

    std::vector<std::string> re;
    for(const std::string f : files) {
        for(const std::string ex : extensions) {
            if(ex == tail(f,ex.size())) {
                re.push_back(std::move(f));
                break;
            }
        }
    }
    return re;
}

int main(int argc, char **argv) {

    std::vector<std::string> v{"main.cpp","main.c","main.py"};
    std::vector<std::string> re = filtered_files(v,{".c",".cpp"});
    for(const std::string s  :re) {
        std::cout << s << '\n';
    }

}

Aucun commentaire:

Enregistrer un commentaire