当前位置:网站首页>C + + generates incremental sequence

C + + generates incremental sequence

2020-12-06 17:44:56 ShellCollector

 

 

Incremental vector Array

 

Native arrays and vector、array Does not support the construction of an incremental array , For example, one contains 0~999 Of size by 1000 Array of .

int ids[1000] = {};
for (int i = 0; i < 1000; ++i)
{
	ids[i] = i;
}

If it is std::vector, It is :

std::vector<int> ids;
ids.resize(1000);
for (int i = 0; i < 1000; ++i)
{
	ids[i] = i;
}

Some people use use lambda Expression to implement

Now introduce C++11 Newly added std::iota, Need to include header file numeric
Possible implementation :
Official documents :https://en.cppreference.com/w/cpp/algorithm/iota

template<class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value)
{
    while(first != last) {
        *first++ = value;
        ++value;
    }
}

Use examples 1, It seems that I can use it :

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

std::vector<size_t> idx(scores.size());
	std::iota(idx.begin(), idx.end(), 0);

I didn't try this one : 

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

int main()
{
	std::vector<int> ivec(10);
	std::iota(ivec.begin(), ivec.end(), 4);
	//for (auto &it: ivec)
	//{
	//	std::cout << it << " ";
	//}

	// Or use the following sentence to output ivec Chinese content 
	std::copy(ivec.begin(), ivec.end(), std::ostream_iterator<int>(std::cout, " "));

	getchar();
	return 0;
}
std::iota(ivec.begin(), ivec.end(), 4);

版权声明
本文为[ShellCollector]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012061742250957.html