Last Updated on 2022-06-26 by Clay
When we got the following error message with deque or vector container of C++ STL (Standard Template Library):
No matching member function for call to 'push_back' error
The error is caused by wrong request object, usually incorrectly pushes the data type that does not conform to the declaration.
Reproduce The Error
We can use the following code to reproduce this error:
#include <vector>
#include <string>
using namespace std;
int main() {
// Init
vector<string> notes;
string sent = "Today is a nice day.";
// Push back
for (int i=0; i<sent.size(); ++i) {
notes.push_back(sent[i]);
}
return 0;
}
Output:
test.cpp:14:15: error: no matching member function for call to 'push_back'
notes.push_back(sent[i]);
The Reason For The Error
This is because the string type is different from the element characters in it. We can use the following code to check the data type:
#include <iostream>
#include <typeinfo>
#include <vector>
#include <string>
using namespace std;
int main() {
// Init
vector<string> notes;
string sent = "Today is a nice day.";
// Push back
printf("typeid(notes).name(): %s\n", typeid(sent).name());
printf("typeid(notes).name(): %s\n", typeid(sent[0]).name());
return 0;
}
Output:
typeid(notes).name(): NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE
typeid(notes).name(): c
As you can see, the one side is string type, the other side is char type.
The correction method is actually very easy, nothing more than converting the data into the data type we declared. In short, we need to push the data that matching the same data type of sequence.
Solutions
Method 1: Declare The Correct Data Type
#include <vector>
#include <string>
using namespace std;
int main() {
// Init
vector<char> notes;
string sent = "Today is a nice day.";
// Push back
for (int i=0; i<sent.size(); ++i) {
notes.push_back(sent[i]);
}
return 0;
}
Method 2: Convert The Data Type
#include <vector>
#include <string>
using namespace std;
int main() {
// Init
vector<string> notes;
string sent = "Today is a nice day.";
// Push back
for (int i=0; i<sent.size(); ++i) {
string s;
s.push_back(sent[i])
notes.push_back(s);
}
return 0;
}
References
- https://stackoverflow.com/questions/1287306/difference-between-string-and-char-types-in-c#:~:text=C%2B%2B%20strings%20can%20contain%20embedded,readable%20and%20easier%20to%20use.
- https://stackoverflow.com/questions/52734630/no-matching-member-function-for-call-to-push-back-error
Pingback: No Matching Member Function For Call To 'Push_Back' | Error No Matching Function For Call To €˜Stdvectorstd__Cxx11Basic_Stringchar Push_Back(IntU0026)€™ - 상위 65개 답변
Thank you very much!!
You’re welcome!