在字符串向量中插入一个字符串
问题描述:
这是我正在尝试编译的代码。我收到此错误:
没有匹配函数来调用'std :: vector< std :: basic_string< char> > :: insert(int,const char [2])'
此行上
dataDictionaryEntryFieldsId.insert(2,B);
我做错了什么?
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?
#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");
}
我的尝试:
我尝试使用字符串变量而不是B并且它不起作用
What I have tried:
I tried using a string variable instead of "B" and it didn't work either
答
正如 enhzflep所建议的,这是第一个不适合的参数。
尝试
As suggested by enhzflep, it is the first parameter that doesn't fit.
Try
#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;
}
或者,使用 C ++ 11
or, using C++11
#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;
}
我发现擦除工作
I found that erase works
it=v.begin() + 1;
v.erase(it);