【问题标题】:vector< vector >: verify that all have equal sizesvector<vector>:验证所有的大小都相等
【发布时间】:2014-03-18 08:37:29
【问题描述】:

是否有 std/boost 算法来验证向量中的所有向量是否具有相同的大小?并且通过扩展,所有元素的属性都是相同的?

在以下示例中,我使用了我正在寻找的假设std::all_equal

typedef std::vector<int> Line;
std::vector<Line> lines;
lines.push(Line(10));
lines.push(Line(11));

auto equalLengths = std::all_equal(lines.begin(), lines.end(), 
 [](const Line& x){ return x.size(); });

(并且通过扩展:

std::vector<MyClass> vec;
auto equal = std::all_equal(std::begin(vec), std::end(vec),
 [](const MyClass& x) { return x.property(); });

)

【问题讨论】:

  • 你可以自己写函数,不会超过10行。
  • 如果您需要一个方形向量,请使用一个向量并在顶部伪造二维索引。
  • @LightnessRacesinOrbit 只是为了迂腐:矩形向量。而且我认为可以有更多的用例,而不仅仅是 2D 矢量。 (它可能只是一个线条容器,其中线条表示为 N 维空间中法线向量的系数,并且 2D 索引不再有意义)否则我同意 Victor。
  • @Xarn:哦,是的,我的意思是矩形,确实。

标签: c++ algorithm vector


【解决方案1】:

怎么样

#include <algorithm> // for std::all_of

auto const required_size = lines.front().size();
std::all_of(begin(lines), end(lines),
    [required_size](const Line& x){ return x.size() == required_size; });

不幸的是,它不适用于空列表,并且您必须以某种方式将所需的大小放入谓词中。

【讨论】:

  • 略短,适用于空容器:std::all_of(begin(lines), end(lines), [lines](const Line&amp; x){ return x.size() == lines.front().size(); }.
【解决方案2】:

我喜欢@ComicSansMS 的回答,但如果您想要一种不太清晰但也适用于空向量的方法,您可以将std::adjacent_find 与自定义谓词一起使用:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<std::vector<int>> vv{{3, 1}, {4, 1}, {5, 9}};

    bool all_same_size = std::adjacent_find(
      vv.cbegin(), 
      vv.cend(), 
      [](const std::vector<int>& a, const std::vector<int>& b) {
        return a.size() != b.size();    // Look for two adjacent elements that
                                        // have different sizes
      }) == vv.cend();

    std::cout << "all same size: " << all_same_size << '\n';
}

【讨论】:

  • @Xarn 我知道,我知道 :)
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 2010-09-20
相关资源
最近更新 更多