将值存储到列表中失败
Fail to store values to the list
似乎属性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++;
}
与容器相关的迭代器、指针和引用无效。否则,只有最后一个迭代器无效。
相关文章:
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 使用大括号初始值设定项列表时,模板参数推断失败
- 从 std::vector<double> 到 Python 列表的转换失败(提升 python)
- C++ 链表合并排序的实现在连接 1 个以上节点的子列表时失败
- 嵌套列表(字符串向量的向量)初始化失败
- 使用初始值设定项列表初始化结构,对于 std::array 失败
- 简单的链接列表删除失败
- std::list::merge() 对于包含对象的列表失败
- 断言失败,列表迭代器不可取消引用
- 使用链接列表实现堆栈,调试断言失败
- 为什么我的列表中的迭代失败
- 类大括号括起来的初始值设定项列表失败
- 在stl列表中调用构造函数失败
- 从初始化器列表初始化unique_ptrs的容器失败,GCC为4.7
- Visual Studio 2012 c++构建失败,但错误列表或输出中没有任何内容
- 调试断言失败!表达式列表迭代器不兼容
- 堆栈列表调试断言失败c++
- 模板初始化列表-查找失败的原因
- <int> 具有初始值设定项列表的 QVector 失败,并显示 3 个项目
- Windows 10的跳转列表失败