繁体   English   中英

映射插入与对类型

[英]map insert with pair type

<int,int>类型的映射中插入元素时,我们必须再次明确地将类型提及为pair。 不是多余的吗?

map<int,int> m1;
//m1.insert(1,1); //NOT OK since the pair type <int,int> not mentioned
m1.insert(pair<int,int>(1,1)); //OK

m1声明为<int,int> 是否有任何实例,其中我们尝试插入除<int,int>之外的任何元素<int,int> eg m1.insert(pair<int,string>(1,"boo")) 如果不是,那么在插入元素时再次写<int,int>是不是多余的?

编辑1:

这里详细解释一个小例子:

template<typename T1,typename T2>
class Test
{
public:
    template<typename T1>
    void fun1()
    {
        cout<<"This is called for T1 templatized fun1"<<endl;
    }
    template <typename T1,typename T2>
    void insert(pair<T1,T2> &obj)
    {
        cout<<obj.first<<" "<<obj.second<<endl;     
    }
};

int main()
{
    Test <int,int>obj; // Even though i have declared obj as type int,int, i am still able to call insert on type int,string
    obj.insert(pair<int,string>(1,"Anurag"));

在这里我们清楚地看到我创建对象obj的类型与我调用insert()的类型不同。 但我不明白成员函数map :: insert()如何确保类型与创建对象的类型相同? 我想到的一种方式是:

template <typename T3=T1,typename T4=T2> //where T1 and T2 are class typenames
void insert2(pair<T3,T4>& obj2)
{
    cout<<"Inside insert2 \n";
}

但即使这样也不允许,因为这是一个函数模板而不是类模板。 我试着查看map的头文件,看看insert的声明但是更加困惑。

insert不是转发功能。 只需使用括号初始化对象:

m1.insert({1, 1});

在C ++ 11中, emplace将转发参数。

m1.emplace(1, 1);

或者在C ++ 03中, make_pair


关于你的编辑:

这是一个非常不准确的地图表示。 更准确的表示将是这样的:

template <typename Key, typename T,
          class Compare = std::less<Key>,
          class Allocator = std::allocator<std::pair<const Key, T>>>
struct Test
{
    using value_type = std::pair<const Key, T>;
    using iterator   = typename std::allocator_traits<Allocator>::pointer;

    std::pair<iterator, bool> insert( const value_type& value )
    {
        // this calls emplace
    }
};

int main()
{
    Test<int, int> test;
    test.insert(std::pair<int, std::string>(1, "hello"));
}

确实给出了编译器错误。 当然,这就是首先提供便利功能std::make_pair原因。

这是多余的,但事实并非如此。 但是,您可以插入元素而无需重新指定<int,int>

这样,编译器足够聪明,可以找出make_pair函数的模板参数:

m1.insert(make_pair(1,1)); // equivalent o m1.insert(make_pair<int,int>(1,1));

或那样:

m1[1] = 1;

问题是:当你声明一个模板变量( pair是一个类型,所以pair<int,int>( 1, 1 )是一个模板变量声明)时,必须指定模板参数。 但是,当你调用一个函数( make_pair实际上是一个函数)时,模板参数是可选的,编译器将尝试确定它们,并且只有在它失败时它才会抱怨。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM