代码之家  ›  专栏  ›  技术社区  ›  Xigma

如何将find\u first\u not\u of与字符串向量一起使用?

  •  -1
  • Xigma  · 技术社区  · 8 年前

    vector<string> data = {"12","12","12","12","13","14","15", "15", "15", "15", "18"};
    

    我试图在数据对象中找到第一个不重复的条目。 例如,数据。首先查找(data.at(0))的_\u not_;如果数据仅为字符串类型(没有容器),则这将起作用。

    如何使用向量类型的对象实现同样的效果。

    我查看了相邻的find和find_if_,但没有从算法库中找到,但没有用。

    非常感谢您的建议。

    2 回复  |  直到 8 年前
        1
  •  2
  •   0x5453 Yuki    8 年前

    你有什么问题 adjacent_find ? 您应该能够将其与反向谓词一起使用:

    std::vector<std::string> data = {"12","12","12","12","13","14","15", "15", "15", "15", "18"};
    
    // Sort data here if necessary
    
    auto itr = std::adjacent_find(data.cbegin(), data.cend(), std::not_equal_to<std::string>{});
    if (itr != data.cend()) {
        std::cout << "First mismatch: " << *itr << " " << *std::next(itr) << std::endl;
    } else {
        std::cout << "All elements equal" << std::endl;
    } 
    

    Wandbox

        2
  •  1
  •   PaulMcKenzie    8 年前

    由于您必须至少浏览一次列表,并且您不知道何时何地会遇到数字的重复(如果有),解决此问题的一种方法是首先收集“统计数据”,然后根据您收集的数据确定第一个非重复数据。

    下面是一个使用 std::unordered_map :

    #include <algorithm>
    #include <unordered_map>
    #include <iostream>
    #include <vector>
    #include <string>
    
    // struct to hold some information on the numbers
    struct info
    {
        std::string number;
        int count;
        int position;
        info(const std::string n, int c, int p) : number(n), count(c), position(p) {}
    };
    
    int main()
    {
    
        std::vector<std::string> data = {"12","12","12","12","13","14","15", "15", "15", "15", "18"};
        std::unordered_map<std::string, info> infoMap;
        std::vector<info> vInfo;
        int pos = 0;
    
        // loop for each data element
        std::for_each(data.begin(), data.end(), [&](const std::string& n) 
        { 
            // insert entry into the map
            auto pr = infoMap.insert(std::make_pair(n, info(n, 0, pos)));    
    
            // bump up the count for this entry.
            ++pr.first->second.count;
    
            // bump up the postion number
            ++pos;
    
        });
    
        // create a vector of the information with a count of 1 item.
        std::for_each(infoMap.begin(), infoMap.end(), [&](std::unordered_map<std::string, info>::value_type& vt) { if (vt.second.count == 1) vInfo.push_back(vt.second); });
    
        // sort this by position
        std::sort(vInfo.begin(), vInfo.end(), [&](const info& pr1, const info &pr2){return pr1.position < pr2.position; });
    
       // output the results
        if ( vInfo.empty() )
            std::cout << "All values are duplicated\n";
        else  
            std::cout << "The first number that isn't repeated is " << vInfo.front().number << "\n";
        }
    

    Live Example

    首先,我们只需简单地遍历向量中的所有条目,然后计算每个条目的计数。此外,我们将该位置存储在原始列表中,其中包含找到该项的位置。

    之后,我们过滤掉计数正好为1的,并将其复制到向量。然后,我们根据它们在原始列表中的位置对该向量进行排序。