I just want you to tell you that I am writing this post after reading many postings regarding the error I've been getting : " conversion from ‘int’ to non-scalar type." But for my own program, I don't get to apply any of the answers out there to fix it. I hope any of you can give me a comment/opinion/suggestion or concern on the following specific code.
vector<double>::iterator a = *max_element(vector1.begin(), vector1.end());
vector<double>::iterator b = *min_element(vector1.begin(), vector1.end());
vector<double>::iterator c = *(nth_element(vector1.begin(), vector1.begin() + vector1.siz
And one last quick question: Isn't the following way correct to print out the value of variable a, b, c respectively? My compiler is saying that there is no match for ‘operator<<’ in ‘std::cout << a....'. I would appreciate your feedback on this too.
cout << a << b << c << endl;
Thank you so much! I will keep watching on this until getting your reply.
The following is my code for your consideration
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
ifstream ifs("foo.txt");
//initiailize a vector of integers:
vector<int> vector1;
double d;
while(ifs >> d)
{
vector1.push_back(d);
}
int allnumb = vector1.size();
for(int i = 0; i < allnumb; i++){
vector<double>::iterator a = *max_element(vector1.begin(), vector1.end());
vector<double>::iterator b = *min_element(vector1.begin(), vector1.end());
vector<double>::iterator c = *(nth_element(vector1.begin(), vector1.begin() + vector1.size()/2, vector1.end()));
cout << a << b << c << endl;
}
return 0;
}
max_element
and the other functions return iterators. You then use *
to dereference those to get the int
values they refer to, and finally try to use those int
values to initialise a different iterator type. That makes no sense, hence the first error.
Then you try to print the iterators, which aren't printable, hence the second error.
Perhaps you want the values:
int a = *max_element(...);
int b = *min_element(...);
int c = *nth_element(...);
cout << a << ' ' << b << ' ' << c << endl; // add spaces for readability
or perhaps you want correctly-typed iterators:
vector<int>::iterator a = max_element(...);
auto b = min_element(...); // a more convenient alternative, since C++11
auto c = nth_element(...);
cout << *a << ' ' << *b << ' ' << *c << endl; // dereference to print the values