声明一个C++ std :: set迭代器

Ibr*_*ish 0 c++ stl

如果我注释行插入(s,10),下面的程序编译正常;

#include <iostream>
#include <iterator>
#include <set>

using namespace std;

template <class T>
void insert(std::set<T>& _s, const T& t) {
    typename std::set<T>::const_iterator i = _s.insert(t);
}

int main() {
    std::set<int> s;
    // insert<int>(s, 10); // line No: 14
}
Run Code Online (Sandbox Code Playgroud)

但如果我取消注释第14行,那么我得到的错误是:

set.cpp:9:54: error: conversion from ‘std::pair<std::_Rb_tree_const_iterator<int>, bool>’ to non-scalar type ‘std::set::const_iterator’ requested

Naw*_*waz 8

insert 您正在使用的重载,返回对,而不是const_iterator:

std::pair<typename std::set<T>::iterator,bool> pair = _s.insert(t);
Run Code Online (Sandbox Code Playgroud)

那很难看,不是吗?使用auto(如果您使用的是C++ 11):

auto pair = _s.insert(t);
Run Code Online (Sandbox Code Playgroud)

可爱,不是吗?

顺便说一句,为什么它返回std::pair而不是迭代器?

因为insert如果它已经存在,可能不会添加要设置的项目.该pair.second告诉你的元素是否被插入或已存在- true而插入,false意味着不插入.该pair.first是告诉您该元素被发现或插入的位置的迭代器.

  • 或者如果你只想要迭代器,用`s.insert(t).first`初始化它.(这是一个'auto`显然是糟糕的工程的情况.它隐​​藏了设计不良的界面的丑陋,但它也隐藏了你实际拥有的类型.例如,在这种情况下,而不是在他尝试时得到错误为了初始化变量,他会在以后尝试使用`ret`时得到它.初始化时的错误远比他以后使用时会出现的错误更清楚.使用`auto`通常更像是反模式.还要别的吗.) (2认同)