4
votes

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
}
1
I know background is probably a good idea so here it is... It was a three part problem. Problem 3: A stock has two parts: Symbol and Price. Design a class Stock that has these two attributes. Your class should have a constructor function which accepts values for the two attributes, accessor functions for returning the Symbol and Price, and a mutator function which changes the price. Give BOTH the interface and the member functions.victor vaughn
Your index variable of the for loop doesn't match unsigned return value of stocks.size(). i (signed int) < stocks.size() (unsigned int)Sambuca
Problem 4: Using the class Stock from Problem 3, provide solutions to the following: a) Implement the 'addstock' function which adds a new stock (stock) to the vector stocks. b)Implement the member function 'getprice' which returns the price of the stock in the vector 'stocks' which has the symbol equal to the parameter symbol.victor vaughn
@sashoalm How about helping new users by helping them improve their first question (which is nowhere near as bad as it could be, even), instead of simply downvoting them? (arne beat me to the edit itself)Angew is no longer proud of SO
@Angew When I see a bad title or question, I downvote it. That's what downvotes are for. Btw I've retracted my downvote since the title got fixed.sashoalm

1 Answers

11
votes

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();
    }
}