如何将find_first_not_of与字符串向量一起使用
How to use find_first_not_of with a vector of string?
假设我有以下对象:
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的计数过滤出来,然后将其复制到向量。然后,我们根据在原始列表中找到的位置进行对矢量进行排序。
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>