Strange error of vector when recieving inputs | Sololearn: Learn to code for FREE!

0

Strange error of vector when recieving inputs

Hi , what does this error show ? " request for member "push_back" in 'adj' , which is non-class type 'std::vector [100005] " I declared a vector (out of main function) and made a for loop to get some inputs : void Defines(){ #define pb push_back } int n,m; const int N =1e5 + 5; vector<int> adj[N]; ... int main(){ Defines(); cin>>n>>m; for(int i=1; i<=m; i++){ int a,b; cin>>a>>b; adj.pb(a); adj.pb(b); } ... }

cpp

4/12/2021 7:02:47 PM

Ali_combination

11 Answers

New Answer

+4

Ali_combination Just to further explain how macros work, they are a pre-processor directive, they are evaluated just prior to compilation of your program. Typically, they are placed at the top of the file outside of any function. The file is parsed for macros prior to being compiled and then the macros are used to do a literal replacement within the program and then compilation occurs. So, with; #define hello "Hello, World!" ... ... cout << hello; The hello text in the file will literally be changed to the value "Hello, World!" so that just before it is compiled it will read. cout << "Hello, World!";

+3

Rohit What's the point of the Defines() function in your code? Putting a macro definition inside a function does nothing. The macro will be defined irrespective of whether you call the Defines() function or not.

+2

XXX i tried to keep the code as similar to the Ali_combination's example code. Yeah I agree with you, there's no point to put macros inside function.

+2

Ali_combination What @XXX pointed out is true, no need to call Defines() inside the main function because macros will be defined irrespectively like he said. Just comment line 20 in my code above and run, you will see it still works so you got the point Example: #include <iostream> void LOL(){ #define hello "Hello world" } using namespace std; int main() { // notice we didn't call the function LOL here cout << hello; } O/P: Hello world

+2

Rohit oh really sorry, I didn't see that it was the OP's code

+1

Hello Ali_combination , adj[N] with square brackets "[ ]" is for defining the size of an array and not vector in c++, for vector we use parenthesis "( )" like adj(N) edit: // check this code to see it /* 2 3 6 5 7 5 4 6 */ // INPUT #include <iostream> #include <vector> using namespace std; void Defines(){ #define pb push_back } int n,m; const int N =1e5 + 5; vector<int> adj(N); int main(){ Defines(); // no need to call, it'll still works cin>>n>>m; for(int i=1; i<=m; i++){ int a,b; cin>>a>>b; adj.pb(a); adj.pb(b); } }

+1

Rohit I got the point fellas..thank you =)

+1

ChaoticDawg thanks for your nice explanation:))

0

Rohit Hello gentleman , thank you so much .

0

XXX hmm..i just wanted my code to be cleaner . So I made a void function and declared a macro definition . When I call it in my main function , I actually use #defines(isnt it the point?)