C ++函数中矢量大小未增加的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C ++函数中矢量大小未增加的问题相关的知识,希望对你有一定的参考价值。
在下面的代码中,我试图将元素添加到字符串,整数和双精度的向量中,但是当我输出向量的大小时,它永远不会超过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 regR"((\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
答案
请考虑将您的代码更改为类似的内容。使用嵌套对太混乱了。然后至少使用std :: tuple。另外,您需要使用对结构的引用,而不是其副本!
struct Item
string name; // Defines item name
int amount; // Defines amount in stock
double price; // Defines price
struct Store_Info // Stores all info for a given item
string store_name;
string location;
// vector<string> = item | vector<int> = stock | vector<double> = price
vector<Item> items;
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 regR"((\w+),(\d+),\W(\d+.\d+))"; // From professor's piazza post
std::smatch m;
std::regex_match(line, m, reg);
Store_Info ¤t_store = stores[i]; // need to be reference and not the copy !
// item name | amount | price
current_store.items.emplace_back(m[1].str(), std::stoi(m[2].str()), std::stod(m[3].str()));
由于此代码不可运行,因此不确定其他错误或问题。
以上是关于C ++函数中矢量大小未增加的问题的主要内容,如果未能解决你的问题,请参考以下文章