c++ - 如何遍历列表函数?

标签 c++ list function for-loop iteration

我正在运行一个测试程序,我在其中创建一个字符串列表并尝试查找哪些字符串具有特定的后缀或前缀。

#include <iostream>
#include <list>
#include <string>

using namespace std;


list<string> beginWith(const string& pre, list <string> test);
list<string> endWith(const string& suf,list <string> test);


int main(){
    list <string> testList(5);
    string suffix = "able";
    string prefix = "M";
    testList.push_back("Agreeable");
    testList.push_back("Doable");
    testList.push_back("Machine");
    testList.push_back("Makeable");
    testList.push_back("Available");

    for(list <string>::const_iterator it = testList.begin(); it != testList.end(); it++){
        cout << *it << endl;        
    }

    for(list <string>::const_iterator it = beginWith(prefix, testList).begin(); it != beginWith(prefix, testList).end(); it++){
        cout << *it << endl;        
    }

    for(list <string>::const_iterator it = endWith(suffix, testList).begin(); it != endWith(suffix, testList).end(); it++){
        cout << *it << endl;
    }

return 0;
}


list<string> beginWith(const string& pre, list<string> test){
    list <string> answer;
    for(list <string>::const_iterator it = test.begin(); it != test.end(); it++){
        if(pre == it->substr(0, pre.length())){
            answer.push_back(*it);
        }
    }

    return answer;

}

list<string> endWith(const string& suf, list <string> test){
    list <string> answer;
    for(list <string>::const_iterator it = test.begin(); it != test.end(); it++){
        if(suf == it->substr(it->length() - suf.length() , it->back())){
            answer.push_back(*it);

        }
    }

    return answer;

}

我声明了一个字符串列表,用第一个 for 循环将它们打印出来。我还有 2 个函数,它们将遍历该列表,然后返回具有特定前缀或后缀的字符串列表。我将使用第二个和第三个 for 循环将它们打印出来。第一个 for 循环正确打印出来,但是,当我打印出第二个和第三个 for 循环时,出现段错误:11。我对如何让这些 for 循环遍历列表函数并打印出内容感到困惑。

最佳答案

beginWithendWith 按值返回一个列表。这使得 for 循环在列表的不同拷贝上调用 begin()end()

关于c++ - 如何遍历列表函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164784/

相关文章:

c++ - 不需要两个函数 for + 重载?

c++ - 编译时检查是否有两个具有相同模板参数的模板实例化

html - css 水平对齐按钮和图标下方的文本

无法将数组值带入函数

javascript - 如何操作 jQuery 单击事件的宽度?

Swift - 在初始化器中调用函数并在外部定义它

c++ - 实现隐式转换为 char* 的 String 类 (C++)

c++ - 异常中的虚方法

java - 如何在Android中使用Retrofit在recyclerView中设置数据

Python - 将列表范围设置为特定值