c++ - STL std::remove_if 编译器失败

标签 c++ c++11 stl

我无法让 std::remove_if 进行编译,如您所见,我选择了另一种工作正常的手摇曲柄方法,编译器错误位于列表底部的代码之后。

任何帮助将不胜感激。

谢谢, 汤姆

#include <iostream>
#include <fstream>
#include <set>
#include <algorithm>
#include <string>

//
// Find the largest compound word composed
// of sub-words from a list.
//
// - read list from file. 
//
// Psuedo Code:
//
// 1. Read Next Word from File.
// 2. Search in list for word formed from word.
// 3. if Found in List
// 4.   if Found Compound is longer then Current Compound
// 5.     Replace
// 6.     Remove all strings less then Current Compound Length 
// 7. 
//

typedef std::set<std::string> StrSet;
typedef StrSet::iterator StrSetIter;


struct if_substr
{
    std::string m_word;
public:
    if_substr(const std::string& w) : m_word(w) { }

    bool operator() (const std::string& str) const
    {
    std::size_t f = m_word.find(str);
    return (std::string::npos!=f && m_word.length()>str.length());
    }

};

struct if_remove
{
    std::string m_word;
public:
    if_remove(const std::string& w) : m_word(w) { }

    bool operator() (std::string str) const
    {
        return m_word.length()>str.length();
    }

};


class FindLongestCompound
{

    std::ifstream m_file;

    StrSet m_words;
    std::string m_current;

public:
    FindLongestCompound(std::string filename)
    {
    m_file.open(filename, std::ifstream::in); 

    if (!m_file)
        throw std::runtime_error("Failed to open file"+filename);
    }


    void Start(void)
    {
    std::string nextWord;
    while(m_file >> nextWord)
    {

        std::cout << "read word: " << nextWord << std::endl;
        if_substr ifSubstr(nextWord);
        StrSetIter srchItem = std::find_if(std::begin(m_words), std::end(m_words),ifSubstr);
        if (srchItem != m_words.end())
        {
        m_current = nextWord; 
        std::cout << "new current: " << m_current << std::endl;


        if_remove ifRemove(m_current);
        std::remove_if(m_words.begin(), m_words.end(),ifRemove);

        #if 0
        StrSetIter j = m_words.begin();
        do 
        {
            if (j->length() < m_current.length()) 
            j = m_words.erase(j);
            else 
            j++;

        } while (j != m_words.end());
        #endif
        } 
        std::cout << "insert next word: " << nextWord << std::endl;
        m_words.insert(nextWord);
    } 
    }

    std::string result() { return m_current; } 

};


int main(int argc, char *argv[])
{
    if (argc<2)
    {
    std::cout << "Please provide filename" << std::endl;
    return -1;
    }

    FindLongestCompound flc(argv[1]);

    flc.Start();

    std::cout << "result: " << flc.result() << std::endl;
} 
--- errors ---
In file included from stackoverflow.C:2:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:38:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:216:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:15:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:2148:26:
error: no viable overloaded '='
                    *__first = _VSTD::move(*__i);
                    ~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~
    stackoverflow.C:91:8: note: in instantiation of function template specialization
'std::__1::remove_if<std::__1::__tree_const_iterator<std::__1::basic_string<char>,
std::__1::__tree_node<std::__1::basic_string<char>, void *> *, long>,
if_remove>' requested here
                    std::remove_if(m_words.begin(), m_words.end(),ifRemove);
                         ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1415:19:
note: candidate function not viable: 'this' argument has type 'const
value_type' (aka 'const std::__1::basic_string<char>'), but method is
not marked const
        basic_string& operator=(const basic_string& __str);
                      ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1422:45:
note: candidate function not viable: 'this' argument has type 'const
value_type' (aka 'const std::__1::basic_string<char>'), but method is
not marked const
        _LIBCPP_INLINE_VISIBILITY basic_string& operator=(const value_type* __s) {return assign(__s);}
                                                ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:1423:19:
note: candidate function not viable: 'this' argument has type 'const
value_type' (aka 'const std::__1::basic_string<char>'), but method is
not marked const
        basic_string& operator=(value_type __c);
                      ^
    1 error generated.

最佳答案

问题不在于您的仿函数,而在于您使用的容器类型。您不能将 std::remove_ifstd::set(在本例中为您的 StrSet)一起使用。

简而言之,std::remove_if 不会删除任何内容,只是更改元素的顺序,以便“删除”的元素仅出现在特定点之后。只有 erase 才能真正消除它们。

但是,std::set 有一个定义的元素顺序,任何操作都不能绕过它。假设您有以下一组按字典顺序排列的字符串:

{ "aaa", "bbb", "ccc", "ddd", "eee" }

现在您尝试将 std::remove_if 与移除所有元音字符串的仿函数一起应用。你最终会得到这样的结果:

{ "bbb", "ccc", "ddd", "aaa", "eee" }
                     ^
                     |
        "removed" elements start here

这适用于例如std::vector 但不是 std::set 因为它会导致一个集合,其元素不再正确排序(“删除”的元素仍然是放!)。所以你会得到一个编译错误。

为了实现您想要的目标,请使用 std::set::erase在一个循环中。它会正常工作,因为只有被删除元素的迭代器无效,所以 end() 仍然有效。

if_remove ifRemove(m_current);
for (StrSet::iterator set_iter = m_words.begin(); set_iter != m_words.end(); )
{
    if (ifRemove(*set_iter))
    {
        set_iter = m_words.erase(set_iter);
    }
    else
    {
        ++set_iter;
    }
}

在 C++11 中,您可以使用 auto 而不是 StrSet::iterator

关于c++ - STL std::remove_if 编译器失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37640501/

相关文章:

c++ - decltype 和静态模板方法

c++ - 智能指针和指向数组的指针

c++ - 无法将派生类存储在基类指针的 vector 中

c++将多个模板类类型限制为派生类

c++ - 如何避免 typedef?

c++ - 调试 CUDA - CudaUnknownError

c++ - 一组元组 (i, v) 使得所有元组具有不同的 i 值

c++ - 如何从 std::deque 释放内存?

c++ - 初始化后的变量是引用吗?

Android 应用程序和开源库