按字母顺序C ++打印结构输入

时间:2014-03-06 12:12:05

标签: c++ sorting struct

我想按字母顺序打印结构中的字符串,我从线程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

我一直在查看代码,但我无法找到错误的位置,任何人都可以看到错误?

1 个答案:

答案 0 :(得分:0)

你越过循环中数组的范围

for (int i = 0; i <= antalShops; ++i) {
//   Problem here ^^

上面的循环将遍历索引01 2,这对于双项数组来说是一对多。这将导致未定义的行为

您对其他排序循环有同样的问题。