int arr[6] = {1, 4, 20, 3, 10, 5};
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
//some stuff...
}
}
//Above code is iterating twice to array.
将数组转换为矢量后。我必须在向量中应用相同的逻辑。
请指导我如何迭代std::vector
。
答案 0 :(得分:0)
It depends on how you want to operate on the elements of std::vector<int>
and whether you need the index information. E.g., if you want to iterate over std::vector<int> v
and want to change the elements, you could use
for( auto& val : v )
{
val = 0;
}
If you do not change the elements, use
for( const auto& val : v )
{
std::cout << val << std::endl;
}
If you need index information, use the index operator []
std::size_t size = v.size();
for( std::size_t i = 0; i < size; ++i )
{
v[i] = i;
}
Now, if you (really?) want to use std::vector<int>
to store your data but need to be fast in a specific loop, maybe you should prefer something like
int* data = v.data();
std::size_t size = v.size();
for( std::size_t i = 0; i < size; ++i, ++data )
{
*data = i;
}