2015-05-20 62 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);