为什么在转换/复制矢量时进行如此多的复制

Yol*_*ola 3 c++ algorithm stl copy-constructor c++11

为什么这么多人要求复制缺点,我预计只会有九个人呢?或者甚至根本没有返回值优化.

struct C
{
    int _i;
    C(int i) : _i(i) {}
    C(const C& other) { cout << "copy cons from " << other._i << " to " << _i << endl; _i = other._i; }
};
int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> vi{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    vector<C> vc;
    transform(vi.begin(), vi.end(), back_inserter(vc), 
        [](int i) 
    { 
        return C(i); 
    });
}
Run Code Online (Sandbox Code Playgroud)

输出:

copy cons from 1 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 1 to - 842150451
copy cons from 2 to - 842150451
copy cons from 3 to - 842150451
copy cons from 4 to - 842150451
copy cons from 5 to - 842150451
copy cons from 6 to - 842150451
copy cons from 7 to - 842150451
copy cons from 8 to - 842150451
copy cons from 9 to - 842150451
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 10

你的载体vc必须生长几次.每次执行此操作时,它会分配更大的内存块,并复制原始元素.

您可以通过使用保留足够的空间来阻止它这样做std::vector::reserve.

vector<C> vc;
vc.reserve(vi.size());
Run Code Online (Sandbox Code Playgroud)

  • @Yola它增长了近两个因素.确切的因素取决于实施. (3认同)