gpt4 book ai didi

c++ - 如何获得两个迭代器之间的元素总数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:46:30 25 4
gpt4 key购买 nike

我编写了一个函数来测试容器中的所有元素是否都是唯一的。

template<class InputIt>
bool all_elements_unique(InputIt first, InputIt last){
std::set<typename std::iterator_traits<InputIt>::value_type> s(first,last);
return s.size() == std::distance(first,last);
}

它有效。但是,size()返回的size_tdistance()返回的difference_type,不属于相同的标志。

 warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

std::distance可能会根据迭代器的方向返回负数。

如果是这样的话,当元素数量超过有符号最大值时,我如何才能可靠地获得两个迭代器之间的元素总数?我在找类似 std::size 的东西, 但它需要整个容器。

最佳答案

If that's the case, how could I reliably get the total number of elements between two iterators, when the amount of elements exceeds the signed maximum?

如果您要处理那么多元素,您真的希望每次调用该函数时都将其复制到一个集合中吗?

我要么将您的容器作为引用传递,要么替换为您的原始方法:

template<class Container>
bool all_elements_unique(Container& c) {
std::set<typename Container::value_type> s(std::begin(c), std::end(c));
return s.size() == c.size();
}

或者进行排序并adjacent_find:

template<class Container>
bool all_elements_unique(Container& c) {
std::sort(c.begin(), c.end());
return std::adjacent_find(c.begin(), c.end()) == c.end();
}

关于c++ - 如何获得两个迭代器之间的元素总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com