Vector Trouble.


Why am I getting this error?

1
2
3
4
5
6
7
#include <iostream>
#include <vector>
#include <cstdlib>

vector<int> group1r;
vector<string> group1;
group1r.insert(cnt,(rand() % group1.size()/2) + 1);






H:\Vecterz.cpp In function `int main()':

177 H:\Vecterz.cpp no matching function for call to `std::vector<int, std::allocator<int> >::insert(int&, unsigned int)'

note H:\Dev-Cpp\include\c++\3.4.2\bits\vector.tcc:92 candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]

note H:\Dev-Cpp\include\c++\3.4.2\bits\vector.tcc:92 void std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, size_t, const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]
The compiler is saying that it cannot find an overloaded member function of vector called insert that takes parameters of the type you have given(int&, unsigned int).

here is is link to the possible vector::insert functions you can use:
http://www.cplusplus.com/reference/stl/vector/insert.html
Because you are calling the wrong function for what you want to do.

Look up the insert method under the vector section of the STL Containers reference. The link is above, thanks to guestgalkan.

I'd bet that you are trying to have cnt elements in the vector, each initialized with your rand call. Study this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <vector>
#include <algorithm> // used for generate & copy
#include <iterator>  // used for the ostream_iterator

using namespace std;

class Rand
{
    int _x;
public:
    Rand( int x ): _x( x ) {}

    int operator ()() {
        // in here you put whatever rand stuff you want:
        return rand() % _x + 1;
    }
};

int main( int argc, char * args[] )
{
    int cnt = 10;
    // init the size of the vector
    vector<int> grouplr( cnt );
    // this one is also inited, just to make sure it's not empty for this example
    vector<string> groupl( cnt );

    // this is the magic you're after:
    generate( grouplr.begin(), grouplr.end(), Rand(groupl.size()/2) );

    // this just dumps the vector's contents to stdout for verification:
    copy( grouplr.begin(),
          grouplr.end(),
          ostream_iterator<int>( cout, " " ) );

    return 0;
}


Also note that if you do not know the size of the vector ahead of time to initialize it, you could use generate_n and a back_inserter to add elements to the vector.
Last edited on
I'm actually trying to insert certain numbers into an element position such as myarray[0].
grouplr.resize(cnt);
Topic archived. No new replies allowed.