按照我下面的写法, cout << (bool)decrptS.insert(1);出编译报错!
#include<queue>
#include<string.h>
#include <set>
using namespace std;
typedef set<int> Set;
int main()
{
Set decrptS;
cout << (bool)decrptS.insert(1);
// cout << decrptS.insert(2);
// cout << decrptS.insert(3);
// cout << decrptS.insert(1);
decrptS.erase(decrptS.begin());
decrptS.erase(decrptS.begin());
decrptS.erase(decrptS.begin());
decrptS.erase(decrptS.begin());
return 0;
}
if(decrptS.insert(1)) 也会报类型转换错误
官文文档显示这个函数有多种类型的返回值,要怎么理解?
PHP中文网2017-04-17 13:12:19
I think the questioner is calling this version of insert:
std::pair<iterator,bool> insert( const value_type& value );
Look at the documentation of pair, it is a generic container with two values.
pair<T1, T2> has two member variables, the type of first is T1, and the type of second is T2.
So, to get bool from pair<iterator,bool>, you only need to remove second.
cout << decrptS.insert(1).second;
Also, by the way, tuple.
Tuple is a generalized version of pair and can hold n values.
std::tuple<int, double, bool, char*> t(1, 3.14, false, NULL);
printf("%f\n", std::get<1>(t)); // 3.140000
std::get<1>(t) = 2.72;
printf("%f\n", std::get<1>(t)); // 2.720000
(Before this, I didn’t know that STL had a function that returned pair...)
高洛峰2017-04-17 13:12:19
Look at the manual, his insert returns a pair, the first seems to be an iterator, and the second is a bool, indicating success or failure
http://en.cppreference.com/w/cpp/container/set/insert