C++11设置了奇怪的行为
C++ 11 set strange behaviour
这是我的代码
#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
重载(比较器应该与用于var1
、var2
订单的比较器相同):
std::set_difference(var1.begin(), var1.end(),
var2.begin(), var2.end(),
inserter(res, res.end()),
comparator{});
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在 c++11 中为 pthread 设置调度参数
- 使用C 11将数组设置为零
- 将C 11设置功能更改为带有转发的现代模板功能是一个好主意
- 是否可以在 C++11 中手动设置 istream 故障位
- 如何使用原子操作fetch_or或test_and_set在指针中设置一点,而在C 11中不使用Amberare_
- 如何使用C++11 std::thread设置堆叠大小
- 如何在本地设置和全局设置之间以C 11 RNG的初始状态进行切换
- 如何在 Windows 7 上的 CodeBlocks 中设置 C++11
- 无法使用std=C++11设置Eclipse Juno C++
- Eclipse Indexer 中的 C++11 设置与 git 冲突
- 在 C++11 中设置 std::线程优先级的便携式方法
- Eclipse Mars - 为C++项目设置默认设置(默认情况下设置 c++11)
- C++11设置了奇怪的行为
- emacs的c++ 11模式或设置
- c++, Mac OS X, Xcode 8: Compile Boost:设置部署目标为OS X 10.11
- c++ 11在公共函数中设置lambda
- 在Mac Capitan (OSX 10.11)上设置Qt 5.7 OpenGL版本
- C++程序检查 IBAN 帐号 - 如何为每个字符设置值:A=>10、B=>11、C=>12
- C++11 吉尼设置