Skip to content

[Solved][C++] No matching member function for call to ‘push_back’ error

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


References

Tags:

Leave a Reply