简体   繁体   English

C ++:向量问题向量

[英]c++: vector of vector issue

I wrote a c++ code where i'm testing the running time of vector push_back. 我编写了一个C ++代码,用于测试矢量push_back的运行时间。 I have a vector of vector. 我有向量的向量。 I called my main vector, mainVec, and embedded vector, subVec. 我称我的主向量mainVec和嵌入式向量subVec。 So, I push backed 2^20 elements into subVec and then push backed subVec 2^20 times into mainVec. 因此,我将2 ^ 20个元素推入subVec中,然后将subVec 2 ^ 20个推入mainVec中。 However, in the loop of subVec-push_back I have a cout command which doesn't get executed. 但是,在subVec-push_back循环中,我有一个cout命令,该命令未执行。 I was hoping you can point out my mistake. 我希望您能指出我的错误。

Here is the code (There is no error in the code, though): 这是代码(尽管代码中没有错误):

vector<int> subVec; 
vector< vector<int> > mainVec;

//Fills the subvector with 2^20 elements
for( size_t i = 0; i < (pow(2,20)+1); ++i) subVec.push_back(i);

//Filling of the maiVec with 2^20 subVec
for( size_t j = 10; j < 21; ++j) {
    cout << pow(2,j) << endl;
    clock_t t1 = clock();

    //2^j times subVec is push_backed for j < 21
    for( size_t k = 0; k < pow(2,j); ++k ) mainVec.push_back( subVec );

    t1 = clock()-t1;

    //Outputting to file
    cout << "\t" << (float(t1) / CLOCKS_PER_SEC) << endl;
    //ofs << pow(2,j) << "\t\t" << (float(t1) / CLOCKS_PER_SEC) << endl;
}

There are several issues with your code. 您的代码有几个问题。

First, you don't need the +1 in the first loop, ie,. 首先,您不需要在第一个循环中使用+1 pow(2,20)+1 . pow(2,20)+1 Since you're starting with 0 and you want 2^20 times, you need to do until i<2^20 . 由于您从0开始并且想要2 ^ 20次,因此需要做直到i<2^20

Second, it's better to calculate the pow s before the loop, otherwise it will calculate them each time and that could take forever. 其次,最好在循环之前计算pow ,否则每次都会计算它们,这可能会永远花费。

Third, you can do 1<<j instead of pow(2,j) . 第三,您可以执行1<<j而不是pow(2,j) Just FYI. 仅供参考。

Forth, and most important, we are talking about a tremenduous amount of memory here. 第四,也是最重要的一点,我们在这里谈论的内存数量过大。 Even your smallest loop is doing 2^30 ints which is 4GB of memory. 即使是最小的循环也要执行2 ^ 30整数,即4GB内存。 My guess is that your program is just killing your computer and the reason it never prints the second cout is that it doesn't get there (because it's trying to use swap file for the memory). 我的猜测是您的程序正在杀死您的计算机,并且它从不打印第二个cout的原因是它没有到​​达那里(因为它正在尝试使用交换文件作为内存)。 Try using smaller numbers, say 2^10 for the first loop, and see if you get the outputs. 尝试使用较小的数字,例如第一个循环为2 ^ 10,并查看是否获得输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM