list.push_back()不工作:引发错误C++

发布于 2025-01-18 19:31:39 字数 682 浏览 2 评论 0原文

#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) {
        }
    }
}

我是初学者,对这种编程语言了解不多。

错误:

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&)'
#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&)'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云淡月浅 2025-01-25 19:31:39

std :: String没有具有类型char的第一个参数的构造函数。

您要么需要声明列表,要么

std::list<char> songlist;

像这样,

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

但在最后一个情况下,您需要调用方法push_back喜欢

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

使用构造函数

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

,也需要在for循环之前将列表的声明放置。否则,在循环中,列表将在循环的每次迭代中重新创建。

例如

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';

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';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文