list.push_back() not working: throws error C++

433 Views Asked by At
#include <iostream>
#include <list>

using namespace std;

string song = "CDE";
int songlength = song.length();
int counter = 0;

int main() {
    cout << songlength << endl;
    for (int i = 0; i < songlength + 1; i++, counter++) {
        list<string> songlist;
        songlist.push_back(song[counter]);
        if (counter <= songlength) {
        }
    }
}

I am a beginner and I do not know much about this programming language.

Error:

error: no matching function for call to 'std::__cxx11::list<std::__cxx11::basic_string<char> >::push_back(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
1

There are 1 best solutions below

0
Vlad from Moscow On

The class std::string does not have a constructor with the first parameter of the type char.

Either you need to declare the list like

std::list<char> songlist;

or like

std::list<std::string> songlist;

But in the last case you need to call the method push_back like

songlist.push_back(std::string( 1, song[counter] ) );

using the constructor

basic_string(size_type n, charT c, const Allocator& a = Allocator());

Also you need to place the declaration of the list before the for loop. Otherwise within the loop the list is created anew in each iteration of the loop.

For example

std::list<char> songlist;
for ( std::string::size_type i = 0; i < songlength; i++ ) {
    songlist.push_back(song[i]);
}

for ( char c : songlist )
{
    std::cout << c;
}
std::cout << '\n';