c++ - 指向其他 vector 元素的指针的 vector

标签 c++ pointers vector

EI 具有将 vector 指针作为参数指针的函数:

void Function(std::vector<type>* aa)

现在在这个函数中,我想从那个 vector 中过滤出数据到另一个 vector ,我想通过改变这个临时 vector 的值来改变原始 vector 的数据。该死的很难理解像这样的东西:

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(&current_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.
}

这不会改变原始值。

最佳答案

我认为您可能无法传达您的意图,所以这需要一个心理答案。

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.
}

关于c++ - 指向其他 vector 元素的指针的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009638/

相关文章:

R:使用自定义顺序按名称重新排序数字向量

c++ - 从字符串中删除空格,不包括 "and ' C++ 对之间的部分

c++ - gcc 6.3 和 clang 4.0 中的 std::get_time() 不适用于完整的月份名称

c++ - 从文件中读取字符串并转换为 bitset<12>

c - 警告 : Incompatible pointer types assigning to 'node_t *' (aka 'struct node *' ) from 'mode_t' (aka 'unsigned int *' )

c - 了解 Newt Widget Kit 中指向指针的 Const 指针

c++ - 用户空间中的 Linux C/C++ 计时器信号处理程序

c - 理解c中两个链表实现之间的区别

c++ - 如何从文本文件中读取数据并将其加载到 vector 中?

string - 将i8的向量转换为Rust中u8的向量? [复制]