C++11设置了奇怪的行为

C++ 11 set strange behaviour

本文关键字:设置 C++11      更新时间:2023-10-16

这是我的代码

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
struct comparator{
    bool operator()(const string& a, const string& b) const
    {
        if(a.length()>b.length()){
            return false;
        }
        else if(a.length()==b.length()){
            return (a<b);
        }
        else{
            return true;
        }
    }
};
void gen_combinations(string& tmp, set<string>& combs)
{
    for (int i=0; i<=tmp.length(); i++)
    {
        for(int k=i; k<=tmp.length(); k++)
        {
            combs.insert(tmp.substr(i, k-i+1));
        }
    }
}
int main()
{
    vector<string> words;
    set<string> combinations;
    set<string> forWord;
    set<string, comparator> result;
    string temp;
    vector<set<string>> container;
    int n;
    cin >> n;
    if(n!=1){
    for(int i = 0; i < n; i++){
        cin >> temp;
        words.push_back(temp);
        gen_combinations(temp, forWord);
        container.push_back(forWord);
        forWord.clear();
    }
    auto difference = [](set<string>& a, set<string>& b, set<string, comparator>& res){
        set_difference(a.begin(), a.end(), b.begin(), b.end(), inserter(res, res.end()));
    };
    for (int i=0; i<n; i++)
    {
        for(int g=0;g<n;g++){
            if(g!=i){
                combinations.insert(container[g].begin(), container[g].end());
            }
        }
        difference(container[i], combinations, result);
        if(result.begin()==result.end()){
            cout << "?";
        }
        else
        {
            cout << *result.begin();
        }
        cout << endl;
        result.clear();
        forWord.clear();
        combinations.clear();
    }
    }
    else
    {
        cin >> temp;
        for(int i=0;i<temp.length();i++){
            result.insert(temp.substr(i,1));
        }
        cout << *result.begin();
    }
    return 0;
}

我用它来定义set<string, comparator> var1;和更多的集合。在填充了这些集合之后,我尝试使用set_difference(),这里有一些输出

可变1

a b e r ar be ea bea ear bear 

可变2

a b d e r ar be ea rd ard bea ear bear eard beard

variable1-variable2-

bea ear bear

其中var1和var2是集合,var1-var2是set_difference()那么,为什么代码的行为如此奇怪呢?(集合之间的差异应为空集合)

p.S。如果我不使用比较器,一切都很好。

使用

std::set<string, comparator> var1 = // ...
std::set<string, comparator> var2 = // ...

您应该使用带有比较器的std::set_difference重载(比较器应该与用于var1var2订单的比较器相同):

std::set_difference(var1.begin(), var1.end(),
                    var2.begin(), var2.end(),
                    inserter(res, res.end()),
                    comparator{});