在c++中插入一个有序的结构体数组

Inserting into a sorted array of structs in C++

本文关键字:一个 数组 结构体 c++ 插入      更新时间:2023-10-16

我必须在c++中使用一个数组来实现一个向量,该数组用于计算输入中唯一单词的数量。它读取输入,然后将单词添加到包含其计数和唯一单词的结构体中,然后将其添加到向量中。我已经成功地实现了插入。问题是我无法让插入/递增唯一字数计数工作(元素没有添加到向量中)。下面是我的代码:

#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include "MyVector.h"
using namespace std;
struct wordCount{
    string val;
    int count;
};
int main(int argc, char** argv) {
  enum { total, unique,individual } mode = total;
  for (int c; (c = getopt(argc, argv, "tui")) != EOF;) {
    switch(c) {
    case 't': mode = total; break;
    case 'u': mode = unique; break;
    case 'i': mode = individual; break;
    }
  }
  argc += optind;
  argv += optind;
  string word;
  Vector<wordCount> words;
  Vector<wordCount>::iterator it;
  int count = 0;
  while (cin >> word) {
    count++;
    if(mode == unique || mode == individual){
      for(it=words.begin();it != words.end();it++){
        if((it-1)->val <= word && it->val >= word){
            // Found word, increment its count
            if(it->val == word){
                it->count++;
                break;
            }
            // Otherwise insert the new unique word
            else{
              cout << "adding unique word" << endl;
              wordCount* wc;
              wc = new wordCount;
              wc->val = word;
              wc->count = 1;
              words.insert(it,*wc);
              break;
            }
        }
      }
    }
  }
  switch (mode) {
    case total: cout << "Total: " << count << endl; break;
    case unique: cout << "Unique: " << words.size() << endl; break;
    case individual:
        for(it=words.begin();it!=words.end();it++){
          cout << it->val << ": " << it->count << endl;}
        break;
  }
}

如果没有看到您的实现,很难说什么Vector。如果我们假设它符合标准容器约定(并且在尝试这样做时没有错误):您从it.begin(), but immediately access it-1开始迭代. That's undefined behavior for a standard container. (I don't know what it will do with your implementation of Vector ',但是需要一些复杂的代码才能使其工作)

在更高的层次上,似乎有一个基本的不一致:你是保持向量排序,但仍然使用线性搜索。如果你在使用线性搜索,没有必要保留向量排序;只使用:

Vector<wordCount>::iterator it = words.begin();
while ( it != words.end() && *it != word ) {
    ++ it;
}
if ( it == words.end() ) {
    //  not found, append to end...
} else {
    //  found, do whatever is appropriate...
}

(虽然我可能会追加到end,恢复迭代器到新插入的元素,并将其视为已找到的元素)

或者,如果要保持向量的排序,则使用二进制搜索,而不是线性搜索

无论哪种情况,将搜索放在单独的函数中。(如果这不是家庭作业,我会说用std::vectorstd::find_ifstd::lower_bound .)

还有,为什么new在最里面的else ?一个更合理的方法是为wordCount提供构造函数(将计数设置为0),并执行如下操作:

if ( ! found ) {
    it = words.insert( wordCount( word ) );
}
++ it->count;

found的定义将取决于您是否使用是否二分搜索。就标准而言,这是:

Vector<wordCount>::iterator it
    = std::find_if( words.begin(), words.end(), MatchWord( word );
if ( it == words.end() ) {
    it = words.insert( words.end(), wordCount( word ) );
}
++ it-count;

Vector<wordCount>::iterator it
    = std::lower_bound( words.begin(), words.end(), word, CompareWord() );
if ( it == words.end() || it->val != word ) {
    it = words.insert( wordCount( word ) );
++ it->count;

你可能应该争取类似的东西,与一个单独的查找函数,返回end或当没有找到值时的插入位置。

这使各种关注点清晰地分开,并避免代码中过多的嵌套。(也许你应该试一试一般情况下避免使用break,而在多个嵌套的if中,则是如此完全不可接受的—你会注意到其中一个其他回答问题的人错过了他们,误解了他们的意思控制流因为它)

为什么不用map呢?这就是它的作用,从一个事物映射到另一个事物。在您的案例中,从string(单词)到int(出现次数)。还是必须用向量?

尝试使用std::map

Counter::Map words;
Counter count(words);
std::for_each(
    std::istream_iterator<std::string>(myInStream /*std::cin*/), 
    std::istream_iterator<std::string>(),
    count);
std::copy(
    words.begin(),
    words.end(),
    std::ostream_iterator<Counter::Map::value_type>(myOutStream /*std::cout*/, "n"));

Counter函子可以像这样

struct Counter
{
    typedef std::map<std::string, size_t> Map;
    Counter(Map& m) : words(&m) {}
    void operator()(const std::string& word)
    {
        Map::iterator it = words->lower_bound(word);
        if (it == words->end() || it->first != word)
            words->insert(it, std::make_pair(word, 1));
        else
            ++it->second; 
    }
    Map* words;
};

使用std::vector

struct CounterVector
{
    typedef std::vector<std::pair<std::string, size_t> > Vector;
    CounterVector(Vector& m) : words(&m) {}
    struct WordEqual
    {
        const std::string* s;
        WordEqual(const std::string& w) : s(&w) {}
        bool operator()(Vector::const_reference p) const {
            return *s == p.first;}
    };
    void operator()(const std::string& word)
    {
        Vector::iterator it = std::find_if(
            words->begin(), words->end(), WordEqual(word));
        if (it == words->end())
            words->push_back(std::make_pair(word,1));
        else
            ++it->second;
    }
    Vector* words;
};
相关文章: