关于 std::d istance 和 std::istream_iterator 的问题

Questions on std::distance and std::istream_iterator

本文关键字:std iterator 问题 istance 关于 istream      更新时间:2023-10-16

网络.cpp是做什么的?

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

注意:wtfile 可以在最佳网络哈希中找到,以下代码段返回最新哈希文件 (#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++;
}

@n.m.我不确定你没有把它放进答案框吗?有了这个和过滤器"answerswers:0",每个人都可以看到这个。所以我会把它作为答案,但所有的凭据都去 n.m.

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

例如,迭代器用于迭代 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个ietarors之间的距离。

现在应该清楚一些了。

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