[英]Dereferencing iterator to pointers correctly
I have a vector of pointers to objects.我有一个指向对象的指针向量。 Each object stores a value and has a toString() function that returns that value as a string.
每个对象存储一个值并有一个 toString() 函数,该函数将该值作为字符串返回。 I have an iterator to go through the vector and I need to extract the value of each object by calling toString().
我有一个迭代器来遍历向量,我需要通过调用 toString() 来提取每个对象的值。 The problem is, I can't figure out how to get the value.
问题是,我不知道如何获得价值。
This function is ultimately supposed to write the number to a file, but I'm using the cout for testing.此函数最终应该将数字写入文件,但我使用 cout 进行测试。
void writeNumbers(vector<Integer*>& input)
{
ofstream write;
write.open("Integers.txt");
vector<Integer*>::iterator iter = input.begin();
for (iter; iter < input.end(); iter++)
{
**std::cout << (*iter)->toString() << std::endl;**
}
write.close();
I get an Access Violation error which points me to the toString() function:
std::string Integer::toString()
{
std::stringstream ss;
ss << *(this)->value;
return ss.str();
}
toString() works fine whenever I don't try to access it through the iterator.
Edit: Value in toString is actually a pointer to a number.编辑: toString 中的值实际上是一个指向数字的指针。
Edit2: New writeNumbers:编辑 2:新的 writeNumbers:
void writeNumbers(vector<Integer*>& input)
{
ofstream write;
write.open("Integers.txt");
vector<Integer*>::iterator iter = input.begin();
for (iter; iter != input.end(); iter++)
{
std::cout << (*iter)->toString() << std::endl;
}
write.close();
}
Final Edit : Alright, the problem turned out to be a borked constructor that was failing to initialize a pointer properly, so I was WAY off base on where the problem actually was.最终编辑:好吧,问题原来是一个无聊的构造函数,它无法正确初始化指针,所以我偏离了问题的实际所在。 :)
:)
Integer::Integer(string input)
{
if(isNaN(input))
value = new int(atoi(input.c_str()));
}
So it should have been !isNaN, plus I fixed the problem of initializing it on bad input:所以它应该是 !isNaN,另外我修复了在错误输入时初始化它的问题:
//New constructor, works 100%
Integer::Integer(string input)
{
if(!isNaN(input))
value = new int(atoi(input.c_str()));
else
value = new int(0);
}
Your toSting() has the issue.您的 toSting() 有问题。 Change
改变
ss <<*(this)->value;
to到
ss << value;
EDIT: This is not an error, but a general advice when using iterators.编辑:这不是错误,而是使用迭代器时的一般建议。 Dont use
<
to check for end, use !=
.不要使用
<
检查结束,使用!=
。
iter < input.end()
It should be like this:应该是这样的:
iter != input.end()
This is because for certain containers, the < operator will not do what you expect.这是因为对于某些容器,< 运算符不会执行您期望的操作。 As a result, at some point you could be dereferencing input.end() itself, which points at nothing.
结果,在某些时候您可能会取消引用 input.end() 本身,这没有任何意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.