Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is the code I'm trying to compile. I get this error:
no matching function for call to ‘std::vector<std::basic_string<char> >::insert(int, const char [2])’

on this line

dataDictionaryEntryFieldsId.insert(2,"B");

What am I doing wrong?

C++
#include "main.hpp"
#include "vector"

using namespace std;

int test(void)
{

vector<string>dataDictionaryEntryFieldsId;

dataDictionaryEntryFieldsId.push_back("A");
dataDictionaryEntryFieldsId.push_back("C");

dataDictionaryEntryFieldsId.insert(2,"B");
}


What I have tried:

I tried using a string variable instead of "B" and it didn't work either
Posted
Updated 1-Dec-16 8:47am
Comments
enhzflep 30-Nov-16 23:17pm    
The first parameter to insert is actually an iterator, rather than an integer. Therefore, if you'd like to add "B" after the other 2 elements, you can instead use:
dataDictionaryEntryFieldsId.insert(dataDictionaryEntryFieldsId.end(),"B");
[no name] 30-Nov-16 23:36pm    
This would suffice an answer with a tiny bit of elaboration.

As suggested by enhzflep, it is the first parameter that doesn't fit.
Try
C++
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
  vector< string > v;
  v.push_back("A");
  v.push_back("C");

  vector< string >::iterator it = v.begin() + 1;
  v.insert( it, "B");

  for (size_t n=0; n<v.size(); ++n)
    cout << v[n] << endl;

}



or, using C++11

C++
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
  vector< string > v;

  v.push_back("A");
  v.push_back("C");

  auto it = v.begin() + 1;
  v.insert( it, "B");

  for (const auto & x : v)
    cout << x << endl;
}
 
Share this answer
 
Comments
JohnnyG62 1-Dec-16 14:11pm    
I tried the non c++11 suggestion and that worked great ! Now I trying to remove a string from a vector.
For example:
v.remove(it);

but get this compile error
‘class std::vector<std::basic_string<char> >’ has no member named ‘remove’
I found that erase works
it=v.begin() + 1;
   v.erase(it);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900