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.
}
这不会改变原始值。
答案 0 :(得分:6)
我认为你可能无法表达你的意图,所以这需要一个心灵的答案。
void Func(std::vector<type> & aa)
{
std::vector<type*> temp;
// I wish <algorithm> had a 'transform_if'
for(int i=0; i<aa.size(); ++i)
{
if( some_test(aa[i]) )
temp.push_back(&aa[i])
}
// This leaves temp with pointers to some of the elements of aa.
// Only those elements which passed some_test(). Now any modifications
// to the dereferenced pointers in temp will modify those elements
// of aa. However, keep in mind that if elements are added or
// removed from aa, it may invalidate the pointers in temp.
}
答案 1 :(得分:2)
不要使用指向vector
的指针,而是使用引用:
void Function(std::vector<type>& aa)
在函数内部,您现在可以照常访问矢量内容。
void Function(std::vector<type>& aa)
{
std::vector<type>& temp = aa;
// if you now append something to temp, it is also appended to aa
aa.push_back(type());
}
我不知道你为什么要两个引用一个向量,但是嘿,你问:)
编辑:删除拼写错误,看评论。感谢名单
答案 2 :(得分:0)
顺便说一下,开始更好地格式化代码。凌乱的代码很难理解,使你很难弄清楚你想要做什么。
这将做你想要的:
void Oglos_Wydarzenie(std::vector<Wydarzenie>& zmienna)
{
std::vector<Wydarzenie *> obecne;
tm AktualnyCzas = {0,0,0,0,0,0,0,0,0};
time_t czas;
czas = time(NULL);
localtime_s(&AktualnyCzas,&czas);
for (unsigned i = 0; i < zmienna.size(); ++i) {
if (zmienna[i].dzien == AktualnyCzas.tm_mday &&
zmienna[i].miesiac == AktualnyCzas.tm_mon &&
zmienna[i].rok == AktualnyCzas.tm_year+1900)
{
obecne.push_back(&zmienna[i]);
}
}
std::cout << obecne.size() << std::endl;
obecne[0]->tytul = "Changed"; //<-- this is suppose to change value.
}
你可以用所有指针完成这个,根本没有引用,但它看起来更令人困惑:
void Oglos_Wydarzenie(std::vector<Wydarzenie>* zmienna)
{
std::vector<Wydarzenie *> obecne;
tm AktualnyCzas = {0,0,0,0,0,0,0,0,0};
time_t czas;
czas = time(NULL);
localtime_s(&AktualnyCzas,&czas);
for (unsigned i = 0; i < zmienna->size(); ++i) {
if ((*zmienna)[i].dzien == AktualnyCzas.tm_mday &&
(*zmienna)[i].miesiac == AktualnyCzas.tm_mon &&
(*zmienna)[i].rok == AktualnyCzas.tm_year+1900)
{
obecne.push_back(&((*zmienna)[i]));
}
}
std::cout << obecne.size() << std::endl;
obecne[0]->tytul = "Changed"; //<-- this is suppose to change value.
}