vector of custom type

Hello, I have just registered at this forum. I have some experience with C, but Im very new to C++(and oop as well).

Im creating a vector of a custom class for a parser that Im writing, everything works fine, except that vect.push_back(obj) produces unexpected results.

my code its something like:
1
2
3
4
5
6
7
8
9
  class CToken{...}
  main(){
   vector<CToken> tokenVector;
   ...
   CToken ntoken;
   ...//assign some values to ntoken variables
   ...
   tokenVector.push_back(ntoken);
  }


Is this use of vect.push_back(nobj) correct?

ps.:
sorry for my poor english, Its not my main language;
Last edited on
Yes, that is correct. What unexpected results or problems are you getting? What does your CToken class look like?
CToken looks something like:
1
2
3
4
5
6
7
8
class CToken{
  public:
    bool isOperator; //value or operator
    char opr;
    double value;
  private:
  ...
}


I get random data(on tokenVector[position]) when I do things like:

1
2
3
4
5
6
7
8
   vector<CToken> tokenVector;
   CToken ntoken;
   ...
   ntoken.isOperator = true;
   ntoken.opr = '+';
   ...
   tokenVector.push_back(ntoken);


The content of ntoken its copied or its linked to tokenVector[positionlast+1]?
Last edited on
How are you accessing the data? It should be something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>

class CToken {
    public:
        bool isOperator;
        char opr;
        double value;
};

int main() {
    std::vector<CToken> tokenVector;
    {
        CToken ntoken;
        ntoken.isOperator = true;
        ntoken.opr = '+';
        tokenVector.push_back(ntoken);
    }
    {
        CToken ntoken;
        ntoken.isOperator = false;
        ntoken.value = 1.0;
        tokenVector.push_back(ntoken);
    }

    for (std::size_t i = 0; i < tokenVector.size(); ++i) {
        std::cout << "Token: ";
        if (tokenVector[i].isOperator) {
            std::cout << "Operator " << tokenVector[i].opr << "\n";
        } else {
            std::cout << "Number " << tokenVector[i].value << "\n";
        }
    }

    return 0;
}


Note that there are easier ways of doing the above code, but this is the way you should probably know.
Thank you NT3.
I was dealing with the data in the wrong way.
Last edited on
Topic archived. No new replies allowed.