如何将find_first_not_of与字符串向量一起使用

How to use find_first_not_of with a vector of string?

本文关键字:向量 字符串 一起 not find first of      更新时间:2023-10-16

假设我有以下对象:

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

我正在尝试在数据对象中找到第一个非重复条目。例如,data.find_first_not_of(data.at(0));如果数据仅为字符串类型(没有容器),则可以使用。

如何使用类型向量的对象实现相同的东西。

我从算法库中查看了Adjacent_find和find_if_not,但无济于事。

您的建议非常感谢。

您对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

,因为您必须至少浏览一次列表,并且您不知道何时或何处会遇到数字的副本(如果有的话),这是一种方法解决此问题是首先收集"统计信息",然后从收集的内容中,您可以确定第一个非义务。

这是使用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 duplicatedn";
    else  
        std::cout << "The first number that isn't repeated is " << vInfo.front().number << "n";
    }

实例示例

首先,我们只是简单地浏览向量中的所有条目,然后对每个项目进行计数。此外,我们将位置存储在找到该物品的原始列表中。

之后,我们以恰好1的计数过滤出来,然后将其复制到向量。然后,我们根据在原始列表中找到的位置进行对矢量进行排序。