Inserting strings to vector

19,551

insert should be given an iterator to insert at a certain location. You need to use push_back instead (which is the same as insert with end() as parameter).

edit

You mentioned in the comments:

I do not want to use push_back since I want the strings to be sorted. That is one of the reasons I'm using the vector

I miss the logic in that statement. If you want a sorted container you should be using either std::set or std::map. Use the "multi-" versions if you want repeating values.

Share:
19,551
Kingkong Jnr
Author by

Kingkong Jnr

Joining with the hope to learn. Hope I can contribute as well.

Updated on June 04, 2022

Comments

  • Kingkong Jnr
    Kingkong Jnr almost 2 years

    I am getting a compilation error. I am trying to add strings to a vector and keep them in "sorted order".

    XYZ is my class. addPortEntry

    class XYZ
    {
        public:
            portListFile(string sTmp);
            void addPortEntry(string sPortName, string sDirection);
        private:
            string sPortListFileName;
            vector <string> v_input_ports;
        ...
    };
    
    void XYZ::addP(string sP, string sDir)
    {
        if(sDir == "in")
        {
            v_input_ports.insert(sP);   // Line 42
        }
        ...
    }
    

    Error:

    XYZ.cpp: In member function ‘void XYZ::addP(std::string, std::string)’:
    XYZ.cpp:42: error: no matching function for call to ‘std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::insert(const char [10])’
    /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:93: note: candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Alloc = std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >]
    /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:657: note:                 void std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, size_t, const _Tp&) [with _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Alloc = std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >]