-1

This is my code:

#include <iostream>
#include <string>
#include <bits/stdc++.h>

using namespace std;

int main()
{
string word = "hi";
int i = 0;
vector<string> vec;
for(i ; i < word.length() ; i++)
{
    vec.push_back(word[i]);
}
return 0;
}

I am trying to push each letter of string "hi" into a vector vec using for loop, but, it is throwing an error on the 14th line: "error: no matching function for call to ‘std::vector >::push_back(char&)’"

  • 3
    *Please* read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Dec 06 '20 at 12:24

3 Answers3

0

You get the error because you have a vector of strings, not characters.

Change it to a vector of characters and it should work:

std::vector<char> vec;

As for what you're trying to do, there is a simpler way to do it:

std::vector<char> vec(begin(word), end(word));
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
0

Indexed access ([] operator) on std::string returns char& and not std::string itself.

Vector declared is vector of string so insertion into vector requires string type not char&

If you want to have vector of char, change accordingly

0

The error lies in the fact that you have a std::vector of std::string's, but you are trying to push_back a char. There are multiple solutions to this:

  1. Change your std::vector<string> to a std::vector<char>
  2. Create a new std::string object every time you want to push_back a char like this (This is using an overloaded std::string constructor but there are many more possibilities.):
vec.push_back(string(1,word[i]));

Note: Please consider reading about Why is “using namespace std;” considered bad practice?.

Tom Gebel
  • 597
  • 1
  • 1
  • 10