2015-05-20 61 views
-1

是否可以將insert函數用於vector,但是可以像push_back那樣做一對嗎?插入雙向量

void insert(std::vector<int, std::string>& cont, int value) 
{ 
    std::vector<int>::iterator it = std::lower_bound(
     cont.begin(), 
     cont.end(), 
     value, 
     std::less<int>() 
    ); // find proper position in descending order 

    cont.insert((it, std::make_pair(value,""))); // insert before iterator it 
} 
+2

您是不是要找'的std :: map'? –

+0

@Shamari Campbell你快點去哪裏?在我的帖子中看到一個有效的例子。 –

回答

1

std::vector<int,std::string>是不允許的,你可以將其更改爲std::vector<std::pair<int,std::string>>

此外

std::vector<int>::iterator it = std::lower_bound(cont.begin(), cont.end(), value, std::less<int>()); 

應改爲比較對,並返回std::vector<std::pair<int,std::string>>::iterator

+0

確切地說,矢量模板中的第二個類是一個分配器... –

0

功能可以寫入foollowing方式

#include <iostream> 
#include <vector> 
#include <utility> 
#include <algorithm> 
#include <string> 

std::vector<std::pair<int, std::string>>::iterator 
insert(std::vector<std::pair<int, std::string>> &v, int value, bool before = true) 
{ 
    std::vector<std::pair<int, std::string>>::iterator it; 
    std::pair<int, std::string> pair(value, ""); 

    if (before) 
    { 
     it = std::lower_bound(v.begin(), v.end(), pair); 
    } 
    else 
    { 
     it = std::upper_bound(v.begin(), v.end(), pair); 
    } 

    return v.insert(it, pair); 
} 

int main() 
{ 
    std::vector<std::pair<int, std::string>> v { { 1, "A" }, { 2, "B" } }; 

    for (const auto &p : v) 
    { 
     std::cout << p.first << " \"" << p.second << "\"" << std::endl; 
    } 
    std::cout << std::endl; 

    insert(v, 1); 
    insert(v, 1, false); 
    insert(v, 2); 
    insert(v, 2, false); 

    for (const auto &p : v) 
    { 
     std::cout << p.first << " \"" << p.second << "\"" << std::endl; 
    } 
    std::cout << std::endl; 

    return 0; 
} 

程序輸出是

1 "A" 
2 "B" 

1 "" 
1 "" 
1 "A" 
2 "" 
2 "" 
2 "B" 

至於我,我會聲明函數如下方式

std::vector<std::pair<int, std::string>>::iterator 
insert(std::vector<std::pair<int, std::string>> &v, 
     const std::vector<std::pair<int, std::string>>::value_type &value, 
     bool before = true);