[英]Insert with pair vector
是否可以对vector
使用insert
函数,但可以像对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
}
不允许使用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
功能可以写成下面的方式
#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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.