如何在c ++中插入具有唯一条目的对象向量并对其进行排序?

时间:2017-11-09 04:04:41

标签: c++ algorithm sorting vector

我正在研究一个程序,只有当对象不存在时才将对象插入到对象的向量中。所以为了我已经包括算法标题和使用查找和排序功能我试图执行相同但它给我一个错误,我无法理解和解决。

这是插入函数,它返回一个类字对象,数据是一个字向量。

    Word *WordVector::insert(const string text){
Word newWord(text);
if(data.size()==0)
{
    data.push_back(newWord);
}

else{
    if(find(data.begin(),data.end(),newWord)!=data.end()){
        newWord.increaseCount();
    }
    else data.push_back(newWord);
    std::sort(data.begin(), data.end());
}

return &newWord;

}

它给了我这个错误“在第7行的方法算法文件中无效的二进制表达式操作数('Word'和'const Word')”

    template <class _InputIterator, class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
_InputIterator
find(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
{
    for (; __first != __last; ++__first)
        if (*__first == __value_)
            break;
    return __first;
}

1 个答案:

答案 0 :(得分:0)

我会使用std::lower_bound。它在已排序的容器中返回正确的 insert 位置,以保持元素的排序。

bool insert_sorted(std::vector<int>& v, int n)
{
    // find the correct sorted insert position
    auto insert_itr = std::lower_bound(std::begin(v), std::end(v), n);

    // only insert if not a duplicate
    // test for end() first to make duplicate test safe
    if(insert_itr == std::end(v) || *insert_itr != n)
    {
        v.insert(insert_itr, n);
        return true;
    }

    return false;
}

int main()
{
    std::vector<int> ints;

    for(auto i = 0; i < 10; ++i)
        insert_sorted(ints, hol::random_number(0, 10));

    for(auto i: ints)
        std::cout << i << '\n';
}

示例输出:

0
3
4
7
9
10

要使用此定义类型,您需要定义某些功能,使class 排序并测试(in)相等

例如:

class Word
{
public:
    Word(std::string const& s): s(s) {}

    // to enable sorting
    bool operator<(Word const& w) const { return s < w.s; }

    // enable equality matching
    bool operator==(Word const& w) const { return s == w.s; }
    bool operator!=(Word const& w) const { return s != w.s; }

    // enable printing out
    friend std::ostream& operator<<(std::ostream& os, Word const& w)
    {
        return os << w.s;
    }

private:
    std::string s;
};

bool insert_sorted(std::vector<Word>& v, Word const& w)
{
    // find the correct sorted insert position
    auto insert_itr = std::lower_bound(std::begin(v), std::end(v), w);

    // only insert if not a duplicate
    // test for end() first to make duplicate test safe
    if(insert_itr == std::end(v) || *insert_itr != w)
    {
        v.insert(insert_itr, w);
        return true;
    }

    return false;
}