相关疑难解决方法(0)

std :: remove和erase之间的区别?

我怀疑我想澄清一下.我知道对于不同的行为std::vector之间erase,并std::remove在第一物理载体中删除的元素,减小尺寸和其他只是移动而使容量相同的元素.

这只是出于效率原因吗?通过使用erase,a中的所有元素std::vector将被移位1,从而导致大量复制; std::remove做一个'逻辑'删除并通过移动东西保持向量不变.如果物体很重,这种差异可能很重要,对吧?

c++ stl vector

34
推荐指数
4
解决办法
3万
查看次数

从std :: vector中删除,同时为每个执行a?

迭代的正确方法是使用迭代器.但是,我认为通过擦除,迭代器无效.

基本上我想做的是:

for(iterator it = begin; it != end; ++it)
{
    if(it->somecondition() )
    {
     erase it
    }

}
Run Code Online (Sandbox Code Playgroud)

没有v [i]方法我怎么能这样做?

谢谢

struct RemoveTimedEvent
{
    bool operator()(const AguiTimedEvent& pX, AguiWidgetBase* widget) const 
    {
        return pX.getCaller() == widget;
    }
};

void AguiWidgetContainer::clearTimedEvents( AguiWidgetBase* widget )
{
    std::vector<AguiTimedEvent>::iterator it = std::remove_if(timedEvents.begin(),
        timedEvents.end(), RemoveTimedEvent());
    timedEvents.erase(it, timedEvents.end());

}
Run Code Online (Sandbox Code Playgroud)

c++ vector

28
推荐指数
1
解决办法
9439
查看次数

std :: vector迭代器失效

之前有一些关于这个问题的问题; 我的理解是,调用std::vector::erase只会使处于擦除元素之后的位置的迭代器无效.但是,在擦除元素之后,该位置的迭代器是否仍然有效(当然,前提是它end()在擦除后没有指向)?

我对如何实现向量的理解似乎表明迭代器肯定是可用的,但我不完全确定它是否会导致未定义的行为.

作为我正在谈论的一个例子,下面的代码从向量中删除所有奇数整数.此代码是否会导致未定义的行为?

typedef std::vector<int> vectype;
vectype vec;

for (int i = 0; i < 100; ++i) vec.push_back(i);

vectype::iterator it = vec.begin();
while (it != vec.end()) {
    if (*it % 2 == 1) vec.erase(it);
    else ++it;
}
Run Code Online (Sandbox Code Playgroud)

代码在我的机器上正常运行,但这并不能说服它是有效的.

c++ iterator stl vector

14
推荐指数
1
解决办法
9855
查看次数

是否可以为每个循环擦除c ++ 11中std :: list的元素

我想为每个循环使用新的C++ 11迭代列表的所有元素并删除某些元素.例如

std::list<int> myList;
myList.push_back(1); 
myList.push_back(13);
myList.push_back(9);
myList.push_back(4);

for(int element : myList) {
    if(element > 5) {
        //Do something with the element

        //erase the element
    }else{
        //Do something else with the element
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用for循环执行此操作,还是必须返回迭代器才能实现此目的?

c++ stl c++11

9
推荐指数
2
解决办法
3838
查看次数

C循环优化有助于最终分配

因此,对于我在计算机系统课程中的最终作业,我们需要优化这些forloops,使其比原始版本更快.使用我们的linux服务器,基本等级不到7秒,完整等级不到5秒.我在这里的代码大约需要5.6秒.我想我可能需要以某种方式使用指针来使它更快,但我不是很确定.任何人都可以提供我的任何提示或选项吗?非常感谢!

QUICKEDIT:文件必须保持50行或更少,我忽略了教师所包含的那些注释行.

#include <stdio.h>
#include <stdlib.h>

// You are only allowed to make changes to this code as specified by the comments in it.

// The code you submit must have these two values.
#define N_TIMES     600000
#define ARRAY_SIZE   10000

int main(void)
{
    double  *array = calloc(ARRAY_SIZE, sizeof(double));
    double  sum = 0;
    int     i;

    // You can add variables between this comment ...
    register double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0, …
Run Code Online (Sandbox Code Playgroud)

c optimization loops compiler-optimization debug-mode

8
推荐指数
2
解决办法
5650
查看次数