0

This isn't working. And the reason why is cryptic to me.

PS: Using C++11

http://ideone.com/elopRc

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    struct MyStruct {
        size_t some_num;
        char some_char;
        bool some_bool;
        MyStruct* some_ptr;
    };

    vector<vector<vector<MyStruct>>> three_d_struct_v;

    size_t max_i = 100;
    size_t max_j = 10;
    size_t max_k = 10;

    for(size_t i = 0; i < max_i; i++) {
        for(size_t j = 0; j < max_j; j++) {
            for(size_t k = 0; k < max_k; k++) {
                three_d_struct_v.emplace_back(k, 'x', false, nullptr);
            }
        }
    }


    return 0;
}
ParoX
  • 5,685
  • 23
  • 81
  • 152
  • 3
    `three_d_struct_v` is not a vector of `MyStruct`s, it's a vector of vectors. –  Jan 26 '14 at 19:52
  • 1
    honestly, i'd use a map of maps of vectors and just call it good. [See it live](http://ideone.com/ybV183). or even a map of map of maps, but the madness has to end somewhere. – WhozCraig Jan 26 '14 at 20:06
  • @WhozCraig your ideone runs 20 million in time: 3.59 memory: 555008 (runs out of memory) where as the accepted answer time: 2.87 memory: 3468 – ParoX Jan 26 '14 at 21:17
  • @BHare 20-million *what*, exactly? I've no issues with it, nor does [ideone.com](http://ideone.com/Enfdf4), so I don't know what additional requirements you added. Use whatever works best, but at 555008 and oom, I don't think your implementation is likely spot-on. I used an `unordered_map`, as sorting is somewhat pointless. – WhozCraig Jan 27 '14 at 01:48
  • I had set i to go to 800,000 and j and k to be 5. 20,000,000 million elements. – ParoX Jan 27 '14 at 02:51

1 Answers1

0

Here, three_d_struct_v is of type vector<vector<vector<MyStruct>>>, i.e. a vector of vector<vector<MyStruct>>, so you need to add element of type vector<vector<MyStruct>> (likewise for nested dimensions). However, in your code, you are adding element of type MyStruct directly.

You need to change to something like:

for(size_t i = 0; i < max_i; i++) {
    vector<vector<MyStruct>> v1;
    for(size_t j = 0; j < max_j; j++) {
        vector<MyStruct> v2;
        for(size_t k = 0; k < max_k; k++) {
            MyStruct a = {k, 'x', false, nullptr};
            v2.emplace_back(move(a));
        }
        v1.emplace_back(move(v2));
    }
    three_d_struct_v.emplace_back(move(v1));
}

Check out ideone for the whole code.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • While I understand what the original error was now, I am still getting another: http://ideone.com/elopRc – ParoX Jan 26 '14 at 20:03
  • You should probably want to replace all instances of `v1.emplace_back(x)` with `v1.emplace_back(std::move(x))` to avoid unnecessary copies. – David G Jan 26 '14 at 20:11