Reputation: 33
I have been trying to execute this code, and I am getting an error:
main.cpp:11:19: error: no matching function for call to ‘std::vector<std::__cxx11::basic_string<char> >::push_back(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)’ v.push_back(s[2]);
#include <iostream>
#include<vector>
using namespace std;
int main()
{
string s;
s="abc";
vector<string>v;
v.push_back(s[2]);
cout<<v[0];
return 0;
}
Upvotes: 0
Views: 944
Reputation: 595672
You are trying to push a single char
into a std::vector
of std::string
elements. std::string
does not have a constructor that takes only a single char
as input (but it does have an operator=
that does).
So, you will have to either:
std::vector
to hold char
elements instead of std::string
elements:#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s = "abc";
vector<char> v;
v.push_back(s[2]);
cout << v[0];
return 0;
}
std::string
objects that you are pushing into the std::vector
:#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s = "abc";
vector<string> v;
v.push_back(string(1, s[2]));
//
// or:
// v.push_back(string(&s[2], 1));
//
// or:
// string tmp;
// tmp = s[2];
// v.push_back(tmp);
cout << v[0];
return 0;
}
Upvotes: 0
Reputation: 75062
s[2]
is a character (type char
), so it cannot be inserted to vectors that accept string
.
The constructor of std::string
basic_string( size_type count,
CharT ch,
const Allocator& alloc = Allocator() );
is useful to create strings from one character.
Try this:
#include <iostream>
#include<vector>
using namespace std;
int main()
{
string s;
s="abc";
vector<string>v;
v.push_back(std::string(1, s[2]));
cout<<v[0];
return 0;
}
Upvotes: 1
Reputation: 60208
Indexing into a string like this:
s[2]
gives you a char
, and there's no overload of push_back
for vector<string>
that takes a char
.
Instead, you can use the initializer list constructor for string
like this, to pass a string containing a single character:
v.push_back( { s[2] } );
Upvotes: 1