簡體   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