C++ vector<vector<int> > problem

  • Context: C/C++ 
  • Thread starter Thread starter NeoDevin
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 105K views
NeoDevin
Messages
334
Reaction score
2
I'm having trouble figuring out why some of my integers are behaving crazy.

I have a vector of vectors, declared as

Code:
vector<vector<int> > ph;

In another function, I add a vector of three ints to it using

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

Code:
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,
Devin.
 
Last edited:
Physics news on Phys.org
Also, this is all implemented inside a class, if that has any effect on it.
 
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:
#include <vector>
#include <iostream>

using namespace std;

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

    vector<int> p;
    p.push_back(1);
    p.push_back(2);
    p.push_back(3);

    vector<int> q;
    q.push_back(10);
    q.push_back(20);
    q.push_back(30);
    q.push_back(40);

    ph.push_back(p);
    ph.push_back(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;
    }
}
 
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.
 
Never mind, I figured it out, Thanks