指向其他向量元素的指针的向量
EI 有一个函数,它接受向量的参数指针:
void Function(std::vector<type>* aa)
现在在这个函数中,我想将数据从该向量过滤到另一个向量,并且我想通过改变这个临时向量的值来改变原始向量的数据。该死的,很难理解这样的事情:
void Function(std::vector<type>* aa)
{
std::vector<type*> temp; //to this vector I filter out data and by changning
//values of this vector I want to autmatically change values of aa vector
}
我有这样的事情:
void Announce_Event(std::vector<Event>& foo)
{
std::vector<Event> current;
tm current_time = {0,0,0,0,0,0,0,0,0};
time_t thetime;
thetime = time(NULL);
localtime_s(¤t_time, &thetime);
for (unsigned i = 0; i < foo.size(); ++i) {
if (foo[i].day == current_time.tm_mday &&
foo[i].month == current_time.tm_mon &&
foo[i].year == current_time.tm_year+1900)
{
current.push_back(foo[i]);
}
}
std::cout << current.size() << std::endl;
current[0].title = "Changed"; //<-- this is suppose to change value.
}
这不会改变原始价值。
EI have function which takes as parameter pointer to vector:
void Function(std::vector<type>* aa)
Now inside this function I want to filter out data from that vector to another vector and I want to change data of original vector by changing values of this temporary one. Damn it's hard to understand something like:
void Function(std::vector<type>* aa)
{
std::vector<type*> temp; //to this vector I filter out data and by changning
//values of this vector I want to autmatically change values of aa vector
}
I have something like that:
void Announce_Event(std::vector<Event>& foo)
{
std::vector<Event> current;
tm current_time = {0,0,0,0,0,0,0,0,0};
time_t thetime;
thetime = time(NULL);
localtime_s(¤t_time, &thetime);
for (unsigned i = 0; i < foo.size(); ++i) {
if (foo[i].day == current_time.tm_mday &&
foo[i].month == current_time.tm_mon &&
foo[i].year == current_time.tm_year+1900)
{
current.push_back(foo[i]);
}
}
std::cout << current.size() << std::endl;
current[0].title = "Changed"; //<-- this is suppose to change value.
}
That does not change original value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你可能在表达你的意图时遇到困难,所以这需要一个心灵的答案。
I think you may be having trouble communicating your intentions, so this calls for a psychic answer.
不要使用指向
向量
的指针,而是使用引用:在函数内,您现在可以照常访问向量内容。
我不知道为什么你想要对一个向量进行两个引用,但是嘿,你问了:)
编辑:删除了拼写错误,请参阅评论。谢谢
Do not use a pointer to a
vector
, use a reference instead:inside the function you can now access the vectors contents as usual.
I don't know why you want two references to one vector, but hey, you asked :)
EDIT: removed typo, see comments. thanx
顺便说一句,开始更好地格式化你的代码。凌乱的代码很难理解,并且让你更难弄清楚你想要做什么。
这将执行您想要的操作:
您可以使用所有指针而不使用任何引用来执行此操作,但它看起来更令人困惑:
As an aside, start formatting your code better. Messy code is difficult to understand and makes it harder for you to figure out what you're trying to do.
This will do what you want:
You could do this with all pointers and no references at all, but then it looks much more confusing: