【问题标题】:Print struct inputs in alphabetic order C++按字母顺序打印结构输入 C++
【发布时间】: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 成员。
  • 这不是真实代码(你在哪里用员工初始化商店?),请插入真实代码
  • 我对编码很陌生,所以还有很多我不知道的东西,我在代码中使用的大部分东西都是我从编程课程中学到的。

标签: c++ sorting struct


【解决方案1】:

您超出了循环中数组的范围

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

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

另一个排序循环也有同样的问题。

【讨论】:

  • 这行得通,我以为我已经尝试过了,但显然我做得不对,但非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 2020-08-18
  • 2020-04-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 2017-09-15
相关资源
最近更新 更多