[英]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:在使用
push_back
function 时,我收到以下错误:
error: no matching function for call to
错误:没有匹配的 function 用于调用
'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.问题是你有一个向量并且你试图用一个字符而不是一个字符串来调用 push_back。 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.
您不能将 x 类型的值 push_back 到您的向量,除非该类型可隐式转换为字符串,而且不幸的是,没有用于采用 char 的 std::string 的构造函数。
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.您可以通过将vector<string> 设为vector<char> 或使用字符串而不是char 调用push_back 来解决此问题。
Option 1: Make chr a vector of char instead of a vector of string选项 1:使 chr 成为 char 的向量而不是字符串的向量
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选项 2:使用 push_back 更改代码以使用字符串而不是 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.根据您正在做的事情,选项 1 可能就是您想要的。 If you really need a vector of strings though, option 2 will compile.
如果你真的需要一个字符串向量,选项 2 将编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.