簡體   English   中英

插入矢量項目進行設置

[英]Inserting items of vector to set

我想在c ++中插入vector字符串項來set字符串。 如果向量的項包含'+' ,則應將其添加到一個集合中,否則應將其添加到另一個集合中。 我可以通過逐個迭代向量來做到這一點。 但是我可以通過' set '的' insert '函數的' callback '功能來做到這一點嗎?

struct compare {
    bool operator() (const std::string& str) const{
        if(str.find("+") != std::string::npos) {
            return false;
        return true;
    }
};
std::vector strlist = {"apple","+apple","banana","orange","+graphes"};
std::set<std::string,compare> set1,set2;
set1.insert(strlist.begin(),strlist.end(),compare);

我想創建一個包含項目的set1列表,

apple,
banana,
orange

set2的項目,

+apple
+graphes

您可以使用std::partition_copy ,如下所示:

std::partition_copy(strlist.begin(), strlist.end(),
                    std::inserter(set1, set1.end()),
                    std::inserter(set2, set2.end()),
                    [](const std::string& str) { return str.find("+") != std::string::npos; }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM