I am running hhe following code on codepad.org and I am getting this error. "In member function 'double Xchange::getprice(std::string)': Line 87: warning: comparison between signed and unsigned integer expressions"
This is my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Xchange
{
public:
    Xchange();//does nothing (?)
    double getprice(string symbol);
private:
    vector <Stock> stocks;
};
double Xchange::getprice(string symbol)
{
    for(int i=0; i < stocks.size(); i++) {
        if(stocks[i].getsymbol()==symbol) {
            return stocks[i].getprice();
        }
    }
    return -1; //means not found
}
                Here:
for(int i=0; i < stocks.size(); i++)
i is a signed integer, stocks.size() is unsigned. You can use std::size_t, or, if you want to be more precise, use the vector<Stock>::size_type.
for(vector<Stock>::size_type i=0; i < stocks.size(); i++) { .... }
The problem this warning is trying to prevent is that a negative signed to unsigned conversion yields a large number and is most likely not what you want. Besides that, the numerical range of a signed integer is no the same as that of an unsigned one of the same size.
See C++ types for more information.
Note that this is easier in C++11:
for(const auto& stock : stocks)
{
    if(stock.getsymbol()==symbol) //added getsymbol "()"
    {
        return stock.getprice();
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With