C ++矢量理解

时间:2018-08-08 20:19:54

标签: vector c++14

我目前正在使用codewars.com练习我的编码技能。我解决了其中一个问题,想查看其他人的解决方案,但发现一个我不明白的解决方案。它比我的解决方案好得多,我想了解更多。这样“ * std”到底能做什么。 + = i对min_elements做了什么,以及min元素发生了什么?

long queueTime(std::vector<int> customers,int n){

std::vector<long> queues(n, 0);

  for (int i : customers)
    *std::min_element(queues.begin(), queues.end()) += i;

  return *std::max_element(queues.cbegin(), queues.cend());
}

这是我的解决方案:

#include <iostream>
#include <vector>
#include <array>
using namespace std;
long queueTime(std::vector<int> customers,int n){

int i = 0;                        //start of Queue
int count = 0;                    //keeps track of how many items has been         
processed
int biggest = 0;                  //Last/largest ending item size, add to count at end

int list [n];                     //Declared number of registers by size n
for(int k = 0;k<n;k++)            //sets each existing register to have 0 
items
{
  list[k] = 0;
}
//Start of processing customers, ends when last customer is at register.
for (auto i = customers.begin(); i!=customers.end();)
{
//checks if there are free registers.
for(int index = 0; index<n && i!=customers.end();index++)
  {
if(list[index]==0)
{
  list[index] = *i;
  i++;
}
  }
//Subtract 1 from every register
int temp=0;
for (int k =0;k<n;k++)
{
  if(list[k]!= 0)
  {
    temp = list[k];
    temp = temp-1;
    list[k] = temp;
  }
}
//increase count of items processed
count++;
}
//calculates the largest number of items a customer has amungst the last few 
customers.
for(int j=0;j<n;j++)
{
  if(list[j]>biggest)
  {
    biggest = list[j];
  }
}
//end first part
cout<<"\nCount: "<<count<<" Biggest: "<<biggest<<endl;
cout<<"End Function:" 

<<"\n************************\n*************************** 
*******************\n"<<endl;
//answer if number of items processed + last biggest number of items.
  return count+biggest;

}

1 个答案:

答案 0 :(得分:0)

代码正在将一组整数映射到n存储桶,并最小化分配给给定存储桶的元素的总和。

对于每个客户int i,队列中的最小元素将增加i。然后返回最大的结果队列值。

std::vectorstd命名空间中标识符的qualified name lookup

min_element返回一个iterator。解除引用运算符(*)产生的lvaluecompound assignment operator+=)递增。