简体   繁体   中英

C++,ANTLR and VECTORS

I have an ANTLR rule that would return a vector:

main returns [std::vector<int> v]
        :
        ('ERROR' t3=INT{v.push_back(atoi((const char*)$t3.text->chars));}
        '='t4=INT{v.push_back(atoi((const char*)$t4.text->chars));}
        );

Then I call it from C++ and try to get the vector data.

However, my problem is that ANTLR3 automatically initialized the vector v to NULL, which isn't allowed and gives me an error.

If I generate the C++ output of antlr and try to compile with my project it gives an error.

I manually went to the parsedfile that ANTLR outputs and removed the setting to NULL option and compiled again and everything worked out.

I can possibly see to solutions to this problem:

1) initializing the vector myself from ANTLR (DONT KNOW HOW TO INITIALIZE VECTORS)

2) Prevent ANTLR from initializing my vector (Not sure if it can be done)

3) Always manually go change the initialization (Not good practice)

4) Find another way to return the vector, tried to return a pointer to array I get the following error:

error: conversion from ‘std::vector<int, std::allocator<int> >*’ to non-scalar type ‘std::vector<int, std::allocator<int> >’ requested

Any help?

I think you want to do something like this:

main returns [std::vector<int> *v]
:
@init { v = new std::vector<int>(); }
( rule content, using *v in actions );

ANTLR can then initialize your return value to NULL, which I think it always does. The @init block creates an empty vector for you to use.

Of course, you will want to actually use a smart pointer like shared_ptr to avoid potential memory leaks as well.

You can initialize vectors this way:

vector<int> a(2,3); //vector a contains 2 elements: 3 and 3
a[0] = 4;//vector a contains 2 elements: 4 and 3
vector<int> b;
b = a;

And there are some other ways you can check here: http://www.cplusplus.com/reference/vector/vector/vector/

EDIT:

If you want to initialize with zeros:

vector<int> a(2);

should do the work, the vector a will contain 2 zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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