Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ vector<vector<int> > problem

  1. Oct 5, 2007 #1
    I'm having trouble figuring out why some of my integers are behaving crazy.

    I have a vector of vectors, declared as

    Code (Text):
    vector<vector<int> > ph;
    In another function, I add a vector of three ints to it using

    Code (Text):
    vector<int> p;
    p.push_back(0); p.push_back(0); p.push_back(1);
    And later I try to print out the contents by

    Code (Text):
    int i;
    for(i = 0; i < ph.size(); i++){
    cout << ph[i][0] << " " << ph[i][1] << " " << ph[i][2] << endl;
    } cout << endl;
    and it prints out

    0 0 0x633d50

    where the last one seems to be a random hexadecimal number, or something.

    Does anyone know why this might be happening? Some of my functions seem to be evaluating the third number correctly, and give me the proper result, while others seem to evaluate it as zero, and printing it out gives me gibberish.

    Any help would be greatly appreciated.

    Thanks in advance,
    Last edited: Oct 5, 2007
  2. jcsd
  3. Oct 5, 2007 #2
    Also, this is all implemented inside a class, if that has any effect on it.
  4. Oct 5, 2007 #3
    I think your description is incomplete. You declare a vector of vectors of integers named ph. In a separate function you declare vector of integers named p and add some values to it. These are different vectors. Did you forget to mention that you add p to ph? Later, you print three entries from the vector of vectors, but the << operator i not defined for this so you should get a compile error, yet you don't report any. Did you define one yourself?

    You can also try simpler code and see if it can help you clarify how the vector class behaves:

    Code (Text):

    #include <vector>
    #include <iostream>

    using namespace std;

    int main() {
        vector< vector<int> > ph;

        vector<int> p;

        vector<int> q;


        for (vector< vector<int> >::size_type u = 0; u < ph.size(); u++) {
            for (vector<int>::size_type v = 0; v < ph[u].size(); v++) {
                cout << ph[u][v] << " ";
            cout << endl;
  5. Oct 5, 2007 #4
    Sorry, I made some typo's in my first post, I corrected them to what is in my program now. I've worked with vectors of vectors before, and never had this problem.
  6. Oct 5, 2007 #5
    Never mind, I figured it out, Thanks
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook