功能可以写入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);
您是不是要找'的std :: map'? –
@Shamari Campbell你快点去哪里?在我的帖子中看到一个有效的例子。 –