简体   繁体   中英

C++ : Vector assignment error

According to http://www.cplusplus.com/reference/vector/vector/operator=/ I understand that we can use the '=' operator for assignment of vectors. But running the following code, I get an error. What is going wrong?

Code:

 void checkFunction(map<string, vector<string> > foo){
     vector<string> bar;     
     bar = foo.find("ABC");
     }

Error :

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> >]

The map::find method returns an iterator pointing at the element you search for (stored in a std::pair containing the key as first and value as second ).

To access the vector pointed at by the iterator, you need to dereference it and fetch the second element of the pair.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM