繁体   English   中英

关于 std::distance 和 std::istream_iterator 的问题

[英]Questions on std::distance and std::istream_iterator

Network.cpp 有什么作用?

auto count = std::distance(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>());

注意:wtfile 可以在Best Network Hash 中找到,以下代码返回最新哈希文件 (#236) 的计数为 256。 为什么 ?

// First line was the version number
auto linecount = size_t{1};
auto channels = 0;
auto line = std::string{};
while (std::getline(wtfile, line)) {
    auto iss = std::stringstream{line};
    // Third line of parameters are the convolution layer biases,
    // so this tells us the amount of channels in the residual layers.
    // We are assuming all layers have the same amount of filters.
    if (linecount == 2) {
        auto count = std::distance(std::istream_iterator<std::string>(iss),
                                   std::istream_iterator<std::string>());
        myprintf("%d channels...", count);
        channels = count;
    }
    linecount++;
}

@nm 我不确定你为什么没有把它放到答案框中? 有了它和过滤器“答案:0”,每个人仍然可以看到这一点。 所以我会把它作为答案,但所有凭据都转到 nm

在 C++ 算法和迭代器库中,您可以找到许多与算法结合使用的迭代器和应用程序。

例如,迭代器用于迭代 STL 容器中的一系列元素。 或者作为算法的返回值。 它们的行为有点像指针。 因此,如果您有 2 个std::vectors并且想要将数据从 vec1 复制到 vec2 ,则可以使用:

std::copy(vec1.begin(), vec1.end(), vec2.begin());

如果您要在 int 向量中搜索某些内容,那么您将使用

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>

constexpr size_t VectorSisze = 10U;

int main()
{
    // Define Vecor with VectorSisze elements
    std::vector<int> v(VectorSisze);
    // Fill the vector with consecutive numbers
    std::iota(v.begin(),v.end(),0);

    // Search for entry 
    int searchValue{5};
    std::vector<int>::iterator iterSearch = std::find(v.begin(), v.end(), searchValue);

    // check, if we could find something
    if (iterSearch != v.end()) {
        size_t position = std::distance(v.begin(), iterSearch);
        std::cout << "Value "  << searchValue << " found at position " << position << "\n";

    }
    return 0;
}

请在上面的例子中看到我们使用std::distance来计算 2 个 ietaror 之间的距离。

现在应该有些清楚了。

下一个主题是std::istream_iterator std::istream_iterator也有一个开始。 那就是迭代器,给出了要读取的内容的类型和作为参数,要从中读取的流。

在您的示例std::istream_iterator<std::string>(iss) ,将开始从 iss 读取字符串。 没有函数参数的std::istream_iterator<std::string>()是“end()”迭代器。 因此,您可以从头到尾从流中读取某些内容。 请参阅以下示例:

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

constexpr size_t VectorSisze = 5U;

int main()
{
    // Define Vecor with VectorSisze elements
    std::vector<int> v(VectorSisze);
    // Read 5 int values
    std::copy_n(std::istream_iterator<int>(std::cin), VectorSisze, v.begin());
    std::cout <<  "Second value: " << v[1] << "\n";
    return 0;
}

如果你计算开始和结束之间的距离,那么你就有了元素的数量。

并且因为您的迭代器读取std::string ,您将拥有流中的字符串数量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM