【发布时间】:2020-07-16 22:45:57
【问题描述】:
在下面的代码中,我试图将元素添加到字符串、整数和双精度数的向量中,但是当我输出向量的大小时,它永远不会超过 1。这让我相信它不是在添加元素,而是改变第一个元素?
// Need to show this for the code I'm having issues with
struct Store_Info{ // Stores all info for a given item
string store_name;
string location;
// vector<string> = item | vector<int> = stock || vector<double> = price
pair<pair<vector<string>, vector<int>>, vector<double>> item_stock_price;
Store_Info() = default;
Store_Info(string, string);
string how_many(int);
};
void stock_info(vector<Store_Info> &stores, int n_stores){ // This is the code I need help with
for (int i(0); i<n_stores; i++){
string name; string loc;
int counter(0);
bool active(true);
while(active){
string line;
std::getline (cin,line);
if (line == "")
active = false;
else if (counter == 0){
name = line;
counter++;
}
else if (counter == 1){
loc = line;
stores[i] = Store_Info(name, loc);
counter ++;
}
else{
regex reg{R"((\w+),(\d+),\W(\d+.\d+))"}; // From professor's piazza post
std::smatch m;
std::regex_match(line, m, reg);
Store_Info current_store = stores[i];
pair itemStock = std::get<0>(current_store.item_stock_price);
std::get<0>(itemStock).push_back(m[1].str()); // Defines item name
std::get<1>(itemStock).push_back(std::stoi(m[2].str())); // Defines amount in stock
std::get<1>(current_store.item_stock_price).push_back(std::stod(m[3].str())); // Defines price
//cout << std::get<1>(current_store.item_stock_price).capacity();
}
}
}
}
抱歉,如果格式不正确,这是我的第一篇文章。 感谢您的帮助,谢谢!
编辑:了解输入的内容可能会有所帮助..
使用标准输入,函数读取如下:
(int) 商店:
(店铺名称)
(一个位置)
(商品名称),(数量),$(价格)
例如)
2 家商店:
当地杂货店
加利福尼亚
苹果,2,1.20 美元
商场
密歇根
比萨饼,3,4.00 美元
蛋糕,1,10.45 美元
【问题讨论】:
-
这可能是题外话。但是FWIW,您不能使用
stores[i] = ...来增加向量的大小;那是为了索引到向量的 existing 元素。要更改大小,请使用.push_back(或emplace_back或resize)。切线,见quuxplusone.github.io/blog/2019/02/18/… -
请发送minimal reproducible example。这里有太多与问题无关的代码,而且您没有发布可用于重现问题的完整程序。请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs 了解一些提示。