【发布时间】:2014-03-06 20:24:37
【问题描述】:
我想按字母顺序打印结构中的字符串,我从线程How to alphabetically sort strings? 获得了帮助,用于排序。我的问题是,当我运行编译器时,我得到一个排序的输出,但它包含来自另一个结构的名称。我的代码如下所示:
#include <iostream>
#include <set>
#include <algorithm>
#include <string>
using namespace std;
const int antalShops = 2;
const int antalWorkers = 5;
struct employ {
string workerName; int workerAge;
};
struct theMall{
string shopName; string shopType; int shopSize;
employ workerName; employ workerAge;
};
// Declaration of the structs
theMall Shops[antalShops] = {
{"GameStop","toy", 250,},
{"Frandsen", "cloth", 300,},
};
employ Workers[antalWorkers] = {
{"Andrea valente", 41},
{"Giovanni Pirolli", 25},
{"Marco Cipolli", 33},
{"Jensine Jensen", 19},
{"Andrea Jensen", 99},
};
// Functions for sorting and printing names
void print(const string& item) {
cout << item << endl;
}
void PrintWorkers(employ Workers[]) {
set<string> sortedWorkers;
for(int i = 0; i <= antalWorkers; ++i) {
sortedWorkers.insert(Workers[i].workerName);
}
for_each(sortedWorkers.begin(), sortedWorkers.end(), &print);
}
void PrintShops(theMall Shops[]) {
set<string> sortedShops;
for (int i = 0; i <= antalShops; ++i) {
sortedShops.insert(Shops[i].shopName);
}
for_each(sortedShops.begin(), sortedShops.end(), &print);
}
int main(int argc, const char * argv[])
{
PrintShops(Shops);
}
所以我有工人和商店的结构,但是当我尝试使用 PrintShops(Shops) 函数打印商店名称时,我得到了输出:
Andrea Valente
Frandsen
GameStop
我一直在查看代码,但我找不到错误在哪里,任何人都可以看到错误吗?
【问题讨论】:
-
使用小写的类型标识符和大写的变量是非常混乱的。
-
为什么不使用
std::sort对数组进行排序?或者将它们保存在std::vector中,如果您不想修改原始容器,则将该向量复制到您排序的向量中。 -
您永远不会初始化任何
theMall结构的两个employ成员。 -
这不是真实代码(你在哪里用员工初始化商店?),请插入真实代码
-
我对编码很陌生,所以还有很多我不知道的东西,我在代码中使用的大部分东西都是我从编程课程中学到的。