根据http://www.cplusplus.com/reference/vector/vector/operator=/我明白我们可以使用'='运算符来分配向量。但运行以下代码,我收到一个错误。出了什么问题?
代码:
void checkFunction(map<string, vector<string> > foo){
vector<string> bar;
bar = foo.find("ABC");
}
错误:
error: no match for ‘operator=’ in ‘bar = foo.std::map<_Key, _Tp, _Compare, _Alloc>::find [with _Key = std::basic_string<char>, _Tp = std::vector<std::basic_string<char> >, _Compare = std::less<std::basic_string<char> >, _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::vector<std::basic_string<char> > > >, std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::vector<std::basic_string<char> > > >, key_type = std::basic_string<char>](((const std::map<std::basic_string<char>, std::vector<std::basic_string<char> > >::key_type&)(& std::basic_string<char>(((const char*)"PAR"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))))))’
std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = std::basic_string<char>, _Alloc = std::allocator<std::basic_string<char> >]
std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = std::basic_string<char>, _Alloc = std::allocator<std::basic_string<char> >, std::vector<_Tp, _Alloc> = std::vector<std::basic_string<char> >]
std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_CharT>) [with _Tp = std::basic_string<char>, _Alloc = std::allocator<std::basic_string<char> >, std::vector<_Tp, _Alloc> = std::vector<std::basic_string<char> >]
答案 0 :(得分:4)
map::find
方法返回一个迭代器,指向您搜索的元素(存储在std::pair
中,其中包含密钥first
,值为second
)。
要访问迭代器指向的向量,您需要取消引用它并获取该对的second
元素。
void checkFunction(map<string, vector<string> > foo){
typedef map<string, vector<string> > map_t;
map_t::const_iterator i = foo.find("ABC");
if (i == foo.end()) {
// element not found!
}
vector<string> bar(i->second);
}