如何在 C++ 中使用指向结构的指针向量?

How to use a vector of pointers to a structure in c++?

我有一个作业大约一周后到期。它是关于在源文件所在的目录中制作文本文件的字母计数器(大小写无关紧要)。那么字母的输出应该是,首先,根据出现次数最多的字母,其次,如果有出现次数相同的字母,则按照字母顺序排序。作业页面在这里:http://www.cs.sfu.ca/CourseCentral/135/tjd/a1.html. I already did a program that has the same output (here it is: https://drive.google.com/file/d/0BxuBN4fpoq5LNHIwR2U2elVkdVE/view?usp=sharing)。问题是,正如您从作业页面上看到的那样,我的教授坚持要我们使用向量 Freq_table,它具有指向结构 char_count 的指针。我尝试做一些简单的代码来向向量添加元素,如下所示:

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <vector>

using namespace std;

struct char_count {
    char c;
    int count;
};

typedef vector<char_count*> Freq_table;

int main () {
    char_count A_count = {'A', 0};
    Freq_table.push_back (A_count);
}

但是编译器总是给出这样的信息:

error: expected unqualified-id before '.' token                                      
 Freq_table.push_back (A_count);

我似乎无法解决这个错误。我现在只需要知道将元素添加到具有结构指针的向量的语法是什么。

此致。

你做的是错的,你在做类似

的事情
int.push_back(A_count);

此外,你告诉你的向量你想存储一个指向char_count变量的指针,但你存储了变量本身,因此导致了另一个错误。 在将值推入向量之前,您必须对其进行声明。一个可能的(未经测试的)解决方案是

Freq_table newTable;
newTable.push_back(&A_count);

您已将 Freq_table 声明为类型,而不是实例,因此更改:

typedef vector<char_count*> Freq_table;

至:

vector<char_count*> Freq_table;

要添加到 table,您必须传递 char_count 实例的地址。一种方式是:

char_count* A_count = new char_count; // allocate a new instance...returns the address.
A_count->c = 'A';
A_count->count = 0;
Freq_table.push_back(A_count);

不要忘记,如果用 new 分配,则必须删除向量中的实例,否则会发生内存泄漏。

该作业唯一可取之处是您实际上并不需要使用动态内存。您只能将指针向量用于一个非常适合的目的,即按频率降序对字母进行排序。

向量中的指针将是非拥有 指针。对非拥有指针使用原始指针是合适的,因为那样不会导致内存泄漏。

像这样:

int main(void)
{
    char_count dictionary_order[26];
    for( int i = 0; i < 26; ++i ) dictionary_order[i] = {'A'+i, 0};

    /* read the input, count letters.
       Notice that the matching letter is always at index ch-'A' */


    Freq_table frequency_order;
    for (auto& item : dictionary_order) frequency_order.push_back(&item);

    sort(frequency_count.begin(),
         frequency_count.end(),
         [](char_count* a, char_count* b) -> bool
         {
             return (a->count == b->count)? (a->c < b->c) : (a->count > b->count);
         }
        );

    /* print them out */
}

没有动态分配,因此没有泄漏。而且因为 C++ 以相反的声明顺序销毁局部变量,指向的对象将比指针本身存在的时间更长。

如果您需要容纳可变数量的项目,您可以使用 vector<char_count> 来管理内存,并将指针存储到您的强制指针向量中。当然,如果调整向量的大小,指针将变得无效,因此您需要在开始填充指针向量之前构建整个 "real" 向量。