所以我有一个名为 order 的类,当用户下订单时,我调用该类。
我有另一个名为 orderbook 的类,它是一个订单 vector 。
我想在收到新订单后尝试遍历订单簿以检查是否有重复,但现在我被困在遍历 vector 中。
我正在使用迭代器并将新订单的符号与订单簿符号中的每个订单进行比较。
我读到迭代器就像一个指针,它将返回我的 vector 订单的内存位置,*它会给我订单本身,如果我向它添加一个 .symbol 应该给我订单的符号属性,但是正确现在它甚至不会编译。
我尝试时收到此错误:
../src/oncemore.cpp:123:40: error: 'std::vector<order>::iterator' {aka 'class __gnu_cxx::__normal_iterator<order*, std::vector<order> >'} has no member named 'symbol'
123 | if (_clientOrder.symbol.compare(*it.symbol)==0) {}
| ^~~~~~
下面是代码,我删除了一堆与问题无关的东西。
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <string.h>
#include "windows.h"
#include <vector>
#include <chrono>
#include <algorithm>
using namespace std;
class order {
public:
string orderID;
char buysell;
string symbol;
double price;
int qty;
void newOrder(string &_orderID, char &_buysell, string &_symbol, double &_price, int &_qty){
orderID=_orderID;
buysell=_buysell;
symbol=_symbol;
price=_price;
qty=_qty;
}
};
class orderbook {
private:
string orderID;
char buysell;
string symbol;
double price;
int qty;
vector<order> the_orderbook;
vector<order>::iterator it;
public:
string insert(order &_clientOrder){
for (it = the_orderbook.begin(); it != the_orderbook.end(); it++) {
if (_clientOrder.symbol.compare(*it.symbol)==0) {} <-- this line fails
}
the_orderbook.push_back(_clientOrder);
return "bla";
}
};
int main() {
cout << "!!!Hello once more" << endl; // prints !!!Hello once more
string user_input = "";
string done= "done trading";
string orderID;
string orderaction;
string orderRecvedTime;
char buysell;
string symbol;
double price;
int qty;
string error;
orderbook thebook;
order user_order;
while(user_input.compare(done) != 0) {
cout << "enter order"<< endl;
getline(cin, user_input);
stringstream lineStream(user_input);
lineStream >>orderaction>>orderID>> buysell >> symbol >> price>> qty;
if (orderaction.compare("D") == 0) {
string tag150;
user_order.newOrder(orderID, buysell,symbol,price,qty);
tag150 = thebook.insert(user_order);
cout << "You made a new order."<< endl;
}
return 0;
}
最佳答案
当你写
*it.symbol
因为 .
的运算符优先级高于 *
,所以表达式变为:*(it.symbol)
并且错误说迭代器没有名为 symbol
的成员这是真的。您可以通过执行以下操作强制优先级:
(*it).symbol
甚至更好,通过使用适当的运算符:it->symbol
关于C++ 无法访问由 vector 的迭代器返回的类中的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63369486/