将值存储到列表中失败

Fail to store values to the list

本文关键字:失败 列表 存储      更新时间:2023-10-16

似乎属性test aisbn成功地存储了调用setCode(), setDigit()的数据。但是,当我尝试将这些值存储到list<test> simul

时,问题开始失败。

list属性取setDigit()后面的数字的值,而不取代码。我如何将代码和数字都放入列表属性?我看不出问题在哪里。代码:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <list>
using namespace std;
class test
{
    private:
        string code;
        int digit;
    public:
        //constructor
        test(): code(""), digit(0) { }
        //copy constructor
        test(const test &other):
        digit(other.digit)
        { 
            for(unsigned int i=0; i < code.length(); i++)   
                code[i] = other.code[i];
        }
        //set up the private values 
        void setCode(const string &temp, const int num);
        void setCode(const string &temp);
        void setDigit(const int &num);

        //return the value of the pointer character 
        const string &getCode() const;
        const unsigned int getDigit() const;
};
const string& test::getCode() const
{
    return code;
}
const unsigned int test::getDigit() const
{
    return digit;
}
void test::setCode(const string &temp, const int num)   
{
    if((int)code.size() <= num)
    {
        code.resize(num+1);
    }
    code[num] = temp[num];
}
void test::setCode(const string &temp)  
{
    code = temp;
}
void test::setDigit(const int &num)
{
    digit = num;
}

int main()
{
    const string contents = "dfskr-123";
    test aisbn;
    list<test> simul;
    list<test>::iterator testitr;
    testitr = simul.begin();
    int count = 0;
    cout << contents << 'n';
    for(int i=0; i < (int)contents.length(); i++)
    {
        aisbn.setCode(contents);
        aisbn.setDigit(count+1);
        simul.push_back(aisbn);
        count++;
    }
    cout << contents << 'n';
    /*for(; testitr !=simul.end(); simul++)
    {
        cout << testitr->getCode() << "n";
    }*/
}

看起来你的for循环有问题,你需要修改你的for循环,像这样:

for(testitr = simul.begin(); testitr !=simul.end(); testitr++)
    ^^^^^^^^^^^^^^^^^^^^^^^                         ^^^^^^^^^

虽然push_back不会使std::list的迭代器失效,但我认为在使用迭代器的地方设置迭代器更具可读性。根据您的回复,您还需要修改copy constructor:

test(const test &other): code(other.code), digit(other.digit) {}
                         ^^^^^^^^^^^^^^^^  

使用vector

std::vector<test> simul;
 for(int i=0; i < (int)contents.length(); i++)
    {
        aisbn.setCode(contents);
        aisbn.setDigit(count+1);
        simul.push_back(aisbn);
        count++;
    }
与容器相关的

迭代器、指针和引用无效。否则,只有最后一个迭代器无效。