我是 cpp 矢量新手,我一直遇到这个问题
\nerror: no matching function for call to \xe2\x80\x98push_back(const char [6])\xe2\x80\x99
#include <vector>\n#include <iostream>\nusing namespace std;\nint main() {\n vector<int> names;\n names.push_back("Lewis");\n names.push_back("Mark");\n names.push_back("Reece");\n names.push_back("Max");\n for(int i = 0; i < names.size(); i++)\n cout << names[i] << \'\\n\';\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n这是错误
\ntest.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\ntest.cpp:6:26: error: no matching function for call to \xe2\x80\x98push_back(const char [6])\xe2\x80\x99\n 6 | names.push_back("Lewis");\n | ^\nIn file included from /usr/include/c++/9/vector:67,\n from test.cpp:1:\n/usr/include/c++/9/bits/stl_vector.h:1184:7: note: candidate: \xe2\x80\x98void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]\xe2\x80\x99 <near match>\n 1184 | push_back(const value_type& __x)\n | ^~~~~~~~~\n/usr/include/c++/9/bits/stl_vector.h:1184:7: note: conversion of argument 1 would be ill-formed:\ntest.cpp:6:19: error: invalid conversion from \xe2\x80\x98const char*\xe2\x80\x99 to \xe2\x80\x98std::vector<int>::value_type\xe2\x80\x99 {aka \xe2\x80\x98int\xe2\x80\x99} [-fpermissive]\n 6 | names.push_back("Lewis");\n | ^~~~~~~\n | |\n | const char*\nIn file included from /usr/include/c++/9/vector:67,\n from test.cpp:1:\n/usr/include/c++/9/bits/stl_vector.h:1200:7: note: candidate: \xe2\x80\x98void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]\xe2\x80\x99 <near match>\n 1200 | push_back(value_type&& __x)\n | ^~~~~~~~~\n/usr/include/c++/9/bits/stl_vector.h:1200:7: note: conversion of argument 1 would be ill-formed:\ntest.cpp:6:19: error: invalid conversion from \xe2\x80\x98const char*\xe2\x80\x99 to \xe2\x80\x98std::vector<int>::value_type\xe2\x80\x99 {aka \xe2\x80\x98int\xe2\x80\x99} [-fpermissive]\n 6 | names.push_back("Lewis");\n | ^~~~~~~\n | |\n | const char*\ntest.cpp:7:25: error: no matching function for call to \xe2\x80\x98push_back(const char [5])\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n
小智 7
问题是你使用的是 avector<int>而不是 avector<string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<string> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.push_back("Max");
for(int i = 0; i < names.size(); i++)
cout << names[i] << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)