关于std :: distance和std :: istream_iterator

时间:2019-08-12 03:07:06

标签: c++

Network.cpp是做什么的?

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

注意:wtfile可以在Best Network Hash处找到,以下代码返回 count 作为最新哈希文件(#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++;
}

1 个答案:

答案 0 :(得分:0)

@ n.m。我不确定您是否没有将其放入答案框中?有了它和过滤器“ answers:0”,每个人仍然可以看到这一点。因此,我将其作为答案,但是所有凭据都将转到n.m。

在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个图形对象之间的距离。

这应该现在很清楚了。

下一个主题是std::istream_iteratorstd::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,因此您的流中将拥有字符串数

相关问题