简体   繁体   中英

push_back in vector<string> showing error

I have inserted a string, i want each character to be separately be inserted in the vector string. On using the push_back function i get the following error:

error: no matching function for call to
'std::vector<std::__cxx11::basic_string<char> >::push_back(__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&)' 27 | color.push_back(str[i]);**

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main(){
    int t;
    cin >> t;
    string str;
    char in;
    while(t--){
        cin >> str;
        sort(str.begin(), str.end());

        vector<string> chr;
        for (int i = 0; i < str.size(); i++){
            chr.push_back(str[i]);
        }

        for (int i = 0; i < chr.size(); i++)
            cout << chr[i] << " ";
    }
}

Thank you so much in advance

The problem is that you have a vector and you're trying to call push_back with a character instead of a string. You can't push_back a value of type x to your vector unless that type is implicitly convertible to a string, and unfortunately there is no constructor for a std::string that takes a char.

You can either solve this by making your vector<string> a vector<char> or by calling push_back with a string instead of a char.

Option 1: Make chr a vector of char instead of a vector of string

vector<char> chr;
for(int i = 0; i < str.size(); i++){
  chr.push_back(str[i]);
}

Or

vector<char> chr(str.begin(), str.end());

Option 2: Change code with push_back to use a string instead of a char

vector<string> chr;
for(int i = 0; i < str.size(); i++){
  chr.push_back(str.substr(i, i+i));
}

Based off of what you're doing, option 1 is probably what you want. If you really need a vector of strings though, option 2 will compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM