Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 按类属性(例如名称)搜索类对象的std::vector_C++_Vector_C++03 - Fatal编程技术网

C++ 按类属性(例如名称)搜索类对象的std::vector

C++ 按类属性(例如名称)搜索类对象的std::vector,c++,vector,c++03,C++,Vector,C++03,性能/安全方面的检查是否存在差异 矢量元素使用 带迭代器的for循环 vs std:find_if(…)? 1。for循环 // 1. for loop for (llvm::SmallVectorImpl<myClass>::const_iterator it = v.begin(); it != v.end(); ++it) { if (it->getName() == Name) { // found element

性能/安全方面的检查是否存在差异 矢量元素使用

  • 带迭代器的for循环
  • vs

  • std:find_if(…)?
  • 1。for循环

    // 1. for loop  
    for (llvm::SmallVectorImpl<myClass>::const_iterator it = v.begin();
         it != v.end();
         ++it) {
        if (it->getName() == Name) {
            // found element
            // do smth...
            break;
        }
    }
    
    //1。for循环
    对于(llvm::SmallVectorImpl::const_迭代器it=v.begin();
    它!=v.end();
    ++(it){
    if(it->getName()==Name){
    //发现元素
    //做smth。。。
    打破
    }
    }
    
    vs

    2。std:find_if

    // 2. find if
    llvm::SmallVectorImpl<myClass>::const_iterator it
        = std::find_if(v.begin(),
                       v.end(),
                       StringCheck<llvm::StringRef>(Name));
    if (it != v.end()) {
        // found element
        // do smth...
    }
    
    // StringCheck defined in header...
    
    template <class T>
    struct StringCheck{
        StringCheck(const T &s) : s_(s) {}
        bool operator()(const myClass &obj) const
        {
            return obj.getName() == s_;
        }
    private:
        const T &s_;
    };
    
    //2。发现
    llvm::SmallVectorImpl::const_迭代器
    =std::find_if(v.begin(),
    v、 end(),
    StringCheck(名称));
    如果(it!=v.end()){
    //发现元素
    //做smth。。。
    }
    //标头中定义了StringCheck。。。
    模板
    结构字符串检查{
    StringCheck(const T&s):s_(s){}
    布尔运算符()(常量myClass和obj)常量
    {
    返回obj.getName()==s;
    }
    私人:
    康斯特T&s;
    };
    
    在找到匹配项后,for循环将继续迭代。如果可能有多个匹配项,并且您希望为每个匹配项运行代码,则这可能是一件好事;如果您希望在找到匹配项后停止,并且在大型容器中尽早找到匹配项,则这可能是一件坏事。

    没有什么不同的“安全明智”。对于性能,您必须进行基准测试。最终,
    std::find_if
    将迭代向量,因此我猜没有性能差异。任何这样的差异都足够小,足以导致过早的优化,除非您确实将循环识别为瓶颈,在这种情况下,您将需要自己进行评测。我能看到的唯一区别是迭代器循环将找到所有情况,除非您使用一个中断,
    find_if
    将在第一次出现时隐式停止。您认为
    std::find_if
    是如何实现的-黑魔法?实际上,你不需要猜测——你可以看看实现,它是随编译器提供的。在我的用例中,我希望在第一次匹配后完成迭代,所以我添加了break;在for循环中。