c++ - c+ stl set insert 返回值 如何获取bool类型?
PHP中文网
PHP中文网 2017-04-17 13:10:19
0
3
730

按照我下面的写法, 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中文网
PHP中文网

认证高级PHP讲师

reply all(3)
Ty80

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...)

小葫芦

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

Ty80

if (decrptS.insert(1).second)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!