【问题标题】:C++ Vector understandingC++向量理解
【发布时间】:2019-01-16 05:03:15
【问题描述】:

我目前正在使用 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;

}

【问题讨论】:

  • 这是我的解决方案:
  • std 是一个命名空间。 vector&lt;T&gt; 是该命名空间的一部分,因此是引用( std:: )。 += 只是简写。 x = x + 1x += 1 相同。

标签: vector c++14


【解决方案1】:

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

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

std::vectorqualified name lookupstd 命名空间中的标识符。

min_element 返回一个iterator。取消引用运算符 (*) 生成一个 lvalue,并以 compound assignment operator (+=) 递增。

【讨论】:

  • 最小化总和是什么意思?
猜你喜欢
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多