My aim is to have second_func print to screen both the size parameter and the first vector element contained in the struct passed to it from p_thread create. The issue is with printing the vector element. I have the following code:
#include <iostream>
#include <bits/stdc++.h>
#include <pthread.h>
using namespace std;
void first_func(vector<int>& vect);
void * second_func(void * args);
struct t_args {
vector<int> *vect;
int size;
};
int main() {
vector<int> vect;
vect.push_back(100);
first_func(vect);
return 0;
}
void first_func(vector<int>& vect) {
int record;
pthread_t thread;
struct t_args args;
args.vect = &vect;
args.size = 5;
record = pthread_create(&thread, NULL, &second_func, (void *)&args);
if (record) {
cout << "Error - Not able to create thread." << record << endl;
exit(-1);
}
pthread_join(thread, NULL);
}
void * second_func(void * args) {
struct t_args params = *(struct t_args*) args;
cout << "The value of the size param is " << params.size << endl;
cout << "The value of the first element of the vector is " << params.vect[0] << endl;
pthread_exit(NULL);
}
It causes the following error.
something.cpp: In function ‘void* second_func(void*)’:
something.cpp:38:63: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘std::vector<int>’)
cout << "The value of the first element of the vector is " << params.vect[0]
The full error message is quite long, but this is the gist of it. The program was compiled with the following command:
g++ file.cpp -std=c++11 -lpthread -o file
I am pretty sure this is an issue related to pointers and proper dereferencing syntax, however, after many attempts and altering the syntax, some form of the error persists.
#include <bits/stdc++.h>along with#include <iostream>suggests that you don't know what#include <bits/stdc++.h>does. I recommend against using stuff before you know what it does. You don't necessarily have to know the how, but the what is extremely important. In this case one of the things you should know about#include <bits/stdc++.h>is never use it directly.