o, I am attempting to create an overloaded output operator for a vector. This overloaded output operator is suppose to allow me to print the values in the vector in the form
[Data]^[Index]
so for example if the data at index 3 is 4, it should print 3^4.
However, I can't seem to get it to work correctly. I need it to loop through the entire vector, but I can't seem to detect what I'm doing wrong.
Here is the function within the header.
friend ostream & operator << (ostream &out, const vector<int> &c);
Here is what I have for the function in the source file.
ostream & operator << (ostream &os, const vector<int> &c)
{
for (int i = 0; i < c.size(); i++)
{
os << c.at[i];
os << "^";
os << i;
}
return os;
Finally, here is my main
#include "Polynomial.h"
#include <string>
#include <vector>
#include <utility>
int main()
{
vector<int> poly1(10);
vector<int> poly2(10);
int x;
int y;
int choice;
bool done = true;
std::cout << "What do you wish to do?" << std::endl;
std::cout << "1. Add two polynomials" << std::endl;
std::cout << "2. Multiply two polynomials" << std::endl;
std::cout << "3. Evaluate one polynomial at a given value" << std::endl;
std::cout << "4. Find Coefficent for a given polynomial and given exponent" << std::endl;
std::cout << "5. Find the leading exponent for a given polynomial" << std::endl;
std::cout << "6. Exit "<< std::endl;
std::cin >> choice;
if (choice < 1 || choice > 6)
{
do
{
std::cout << "Invalid entry: please reenter choice" << std::endl;
std::cin >> choice;
} while (choice < 1 || choice > 6);
}
if (choice == 1)
{
std::cout << "Please input the first polynomial in the form of: (non-zero coefficient, exponent) pairs" << std::endl;
do
{
std::cin >> x >> y;
poly1.at(y) = x;
std::cout << "done?" << std::endl;
std::cin >> done;
} while (done == false);
std::cout << poly1 << std::endl;
}
if (choice == 2)
if (choice == 3)
if (choice == 4)
if (choice == 5)
if (choice == 6)
system("pause");
I believe that my issue lies somewhere within my main or within the source file, though I haven't worked with overloaded output operators in a very long time, so I'm not sure exactly what needs to be fixed.
There is no problem with your code except that at is function so you cannot use subscript operator with that,hence correct code for the above problem is :
#include <iostream>
#include <string>
#include <vector>
using namespace std;
ostream & operator << (ostream &os, const vector<int> &c)
{
for (int i = 0; i < c.size(); i++)
{
os << c.at(i);
os << "^";
os << i;
}
return os;
}
int main()
{
std::vector<int> v{1,2,3};
std::cout<<v<<std::endl;
return 0;
}
The problem with your code is somewhere else and it's actually hard to find in the first glimpse.
Here :
os << c.at[i];
std::vector::at is a function and it's the same as std::vector operator [], but it's a function and you can't use it like this. change it to :
os << c.at(i); //or os << c[i];
Two minor things to take care of :
it's better to print some delimiter(like -) when you print each value^index because it's hard to read this way.
in this line for(int i = 0; i < c.size(); i++) to avoid getting '<' : signed/unsigned mismatch warning change it to for(unsigned int i = 0; i < c.size(); i++). std::vector::size returns size_type which is an unsigned integral type.
Related
I have to implement this simple Minimum class which keeps track of min and total, however I keep receiving this error: "error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream') and 'Minimum')". Is there a way to solve this issue? And it looks like it's coming from overloading << operator but I can't see where the problem is. Any help would be appreciated thank you!
#include <iostream>
#include <climits>
using namespace std;
class Minimum {
private :
int min;
int total;
public :
Minimum(int m = INT_MAX, int t = 0){
min = m;
total= t;
}
friend ostream& operator<<(ostream& os, Minimum& m) {
os << "Total = " << m.total << ", " << "min = " << m.min;
return os;
}
Minimum& operator+=(int num) {
total += num;
if (num < min) {
num = min;
}
return *this;
}
Minimum& operator++() {
total++;
return *this;
}
Minimum operator++(int) {
Minimum temp = *this;
total++;
return *this;
}
bool operator==(const Minimum& m) const {
return ((total == m.total) && (min == m.min));
}
bool operator!=(const Minimum& m) const {
return !(*this == m);
}
};
int main() {
Minimum m;
cout << m << endl;
m +=8;
cout << m << endl;
m +=6;
cout << m << endl;
m += 4;
cout << m << endl;
m += 5;
cout << m << endl;
cout << m++ << endl;
cout << m << endl;
cout << ++m << endl;
cout << m << endl;
(m += -10) += 3; // 2 calls chained together
cout << m << endl;
Minimum copy = m;
cout << copy << endl;
if (m != copy)
cout << "Different" << endl;
else
cout << "Equal" << endl;
}
You get this error here:
cout << m++ << endl;
That's because m++ returns a Minimum r-value and the operator you defined expects a non-const l-value to Minimum (i.e. Minimum&).
Change it to:
friend ostream& operator<<(ostream& os, Minimum const & m)
This works because const l-values bind to r-values.
Also, most probably you have a bug in your post-increment operator as you should return the old value:
Minimum operator++(int) {
Minimum temp = *this;
total++;
//return *this;
return temp;
}
I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.
I declared a vector<string> and I cannot even compile it. I tried many ways but none of them worked.
I'm trying to write out the x.surname.push_back(word)[i] but it's definetly written wrongly and I have no idea how to write it properly and make it possible to compile.
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number, i = 0;
string word;
struct donators {
vector<string> surname;
vector<int> amount;
} x;
cout << "How many donators do you want to register? " << endl;
cin >> number;
for (i = 0; i < number; i++) {
cout << "Surname: ";
cin >> word;
x.surname.push_back(word)[i];
cout << "Amount: ";
x.amount.push_back(i);
cin >> x.amount[i];
}
cout << "OUR GORGEUS DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] >= 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
}
else if (x.amount[i] < 10000) {
cout << "Lack of surnames!" << endl;
}
}
cout << "OUR CASUAL DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] < 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
} else if (x.amount[i] >= 10000) {
cout << "Lack of surnames!" << endl;
}
}
return 0;
}
And one more thing. How to make sentence "Lack of surnames!" to be written out once? In some cases, it is written out twice or more times what is redundant.
You are putting [i] at seemingly random places in your code. Such as in x.surname.push_back(word)[i];. Don't add things like this to your code if you're unsure about what they're doing.
The x.surname(word)[i] construct are also wrong. What's x.surname(word) supposed to be? This syntax is for function calls. surname, however, is not a function. It's a std::vector<std::string>. Just put x.surname[i] instead.
And one more thing. How to make sentence "Lack of surnames!" to be
written out once? In some cases, it is written out twice or more times
what is redundant.
That's because you write it for every donor that doesn't fit the criterion. Instead, keep track if any donor fits the criterion and only print it when none ends up fitting. You can do it like this:
bool HasGorgeousDonators = false;
And then in the loop:
if (x.amount[i] >= 10000)
{
cout << "Surname: " << x.surname[i];
cout << "Amount: " << x.amount[i] << endl;
HasGorgeousDonators = true;
}
And after the loop:
if (!HasGorgeousDonators)
cout << "Lack of surnames!" << endl;
Likewise for the other loop. Also, please consider the following Q&A:
Why is "using namespace std;" considered bad practice?
It seems like you are writing C with some C++ help functions. However C++ is a different language. Sure, it supports some C structures, but there's so much more.
Take a look at some of my suggestions for implementation and compare it to your code:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
T ReadCin(std::string_view const& sv = "") {
T retVal;
if (!sv.empty()) std::cout << sv;
std::cin >> retVal;
return retVal;
}
class Donator {
private:
std::string surname{};
int amount{};
public:
constexpr bool IsGenerous() const noexcept { return amount >= 10000; }
void Read() noexcept {
surname = ReadCin<decltype(surname)>("Surname: ");
amount = ReadCin<decltype(amount)>("Amount: ");
}
friend std::ostream& operator<<(std::ostream& out, Donator const& donator) noexcept {
out << "Surname: " << donator.surname << ", " << "Amount: " << donator.amount;
return out;
}
};
int main() {
std::vector<Donator> donators(ReadCin<int>("How many donators do you want to register?\n"));
for (auto& donator : donators) donator.Read();
std::cout << "OUR GENEROUS DONATORS:\n";
std::copy_if(std::cbegin(donators), std::cend(donators), std::ostream_iterator<Donator>(std::cout, "\n"),
[](Donator const& donator) { return donator.IsGenerous(); });
std::cout << "OUR CASUAL DONATORS:\n";
for (auto const& donator : donators) if (!donator.IsGenerous()) std::cout << donator << '\n'; //alternative
}
I tried to include some of the possibilities using C++. I would really advise you to get a good book on C++.
I'm writing a program which includes a 2D vector of objects:
class Obj{
public:
int x;
string y;
};
vector<Obj> a(100);
vector< vector<Obj> > b(10);
I've stored some values of vector a in vector b.
I get an error when I try to print it out like this:
for(int i=0; i<b.size(); i++){
for(int j=0; j<b[i].size(); j++)
cout << b[i][j];
cout << endl;
}
error info:
D:\main.cpp:91: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and '__gnu_cxx::__alloc_traits >::value_type {aka Obj}')
cout << b[i][j];
^
Your problem is not related to vectors, it is related to sending object(s) of some user defined type Obj to the standard output. When you send an object to the output stream using the operator<< as you do with:
cout << b[i][j];
the stream does not know what to do with it as none of the 12 overloads accepts a user defined type Obj. You need to overload the operator<< for your class Obj:
std::ostream& operator<<(std::ostream& os, const Obj& obj) {
os << obj.x << ' ' << obj.y;
return os;
}
or even a vector of Objs:
std::ostream& operator<<(std::ostream& os, const std::vector<Obj>& vec) {
for (auto& el : vec) {
os << el.x << ' ' << el.y << " ";
}
return os;
}
For more info on the subject check out this SO post:
What are the basic rules and idioms for operator overloading?
This has nothing to do with your vectors.
You are trying to print an Obj, but you didn't tell your computer how you would like it to do that.
Either print b[i][j].x and b[i][j].y individually, or overload operator<< for Obj.
There is no cout::operator<< that takes a class Obj as a right hand side. You could define one. Simplest solution is to send x and y to cout separately. But use range-based for-loops!
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Obj {
public:
int x;
string y;
};
vector<vector<Obj>> b(10);
void store_some_values_in_b() {
for (auto& row : b) {
row.resize(10);
for (auto& val : row) {
val.x = 42; val.y = " (Ans.) ";
}
}
}
int main() {
store_some_values_in_b();
for (auto row: b) {
for (auto val : row) {
cout << val.x << " " << val.y;
}
cout << endl;
}
}
Maybe like below
for(int i=0; i<b.size(); i++){
for(int j=0; j<b[i].size(); j++)
cout << "(" << b[i][j].x << ", " << b[i][j].y << ") ";
cout << endl;
}
I'm trying to overload the << operator for the display function call.
Heres my code:
#include <iostream>
#include <cstring>
using namespace std;
// global variable
const int MAX = 3;
// class definition
class CString{
char str[MAX+1];
public:
CString(char* param){
if(param == nullptr){
str[0] = '\0';
return;
}
strncpy(str,param,MAX);
str[MAX] = '\0';
}
void display(ostream& os){
os << str;
}
};
// << operator overloading
ostream& operator << (ostream& os, CString& cs){
static int call = 0;
os << call << ": ";
cs.display(os);
call++;
return os;
}
void process(char* parm){
CString cs(parm);
// here is where my issue is
cs.display(cout);
cout << endl;
}
//----------------------------------------------------------------
int main(int argc,char *argv[]){
cout << "Command Liine : ";
for(int arg = 0; arg < argc ; arg++){
cout << " " << argv[arg];
}
cout << endl;
if( argc == 1){
cout << "Insufffiecentnumber of arguemnts (min1)" << endl;
return 1;
}
cout << " Maxium numver of characters stored: " << MAX << endl;
for(int arg = 1; arg < argc; arg++){
process(argv[arg]);
}
return 0;
}
EDIT:
Here is the correct output and the output I have:
Correct:
Command Line : w1 oop345 btp305
Maximum number of characters stored : 3
0: oop
1: btp
Mine:
Command Line : w1 OOP345 DBS305
Maxium number of characters stored: 3
OOP
DBS
I'm having an issue with my << operator not working, I can't seem to figure it out. The ostream& operator<<(ostream& os, CString& cs) does not seem to be loading its syntax.
Question:
Does anyone know where my mistake has been made?
You wrote a correct overloading of << operator, but in method process() you used a public method display() of class CString instead of using << operator directly.
Just change one line in method process():
cs.display(cout); to: cout << cs;
void process(char* parm){
CString cs(parm);
// here is where my issue is
cout << cs;
cout << endl;
}
P.S. you do not need method CString::display at all as you already overload << operator for this class.