вид C++ со структурами

Вы можете использовать Series.str.get_dummies :

df.Colour.str.get_dummies().replace({1:'Yes', 0:'No'})

   Blue Green Red
0   No    No  Yes
1   No   Yes   No
2   No   Yes   No
3  Yes    No   No
4   No    No  Yes

15
задан animuson 4 September 2012 в 21:27
поделиться

5 ответов

You should use C++'s standard sort function, std::sort, declared in the header.

When you sort using a custom sorting function, you have to provide a predicate function that says whether the left-hand value is less than the right-hand value. So if you want to sort by name first, then by ID, then by amount due, all in ascending order, you could do:

bool customer_sorter(Customer const& lhs, Customer const& rhs) {
    if (lhs.Name != rhs.Name)
        return lhs.Name < rhs.Name;
    if (lhs.Id != rhs.Id)
        return lhs.Id < rhs.Id;
    return lhs.AmountDue < rhs.AmountDue;
}

Now, pass that function to your sort call:

std::sort(customers.begin(), customers.end(), &customer_sorter);

This assumes you have an STL container (and not an array, like you have in your sample code) called customers containing customers.

37
ответ дан 1 December 2019 в 00:14
поделиться

Часто упускается из виду, что на самом деле вы можете использовать функции диапазона STL с массивами на основе C, как в вашем примере. Таким образом, вам фактически не нужно переходить к использованию контейнера на основе STL (я не буду обсуждать преимущества этого здесь: -)).

Итак, основываясь на ответе Криса, вы можете вызвать sort как следует:

std::sort( customers, customers+Count, &customer_sorter);
13
ответ дан 1 December 2019 в 00:14
поделиться

Вам нужно только написать функцию сравнения, которая сравнивает два типа CustomerProfile. Когда у вас есть эта функция, вы можете использовать сортировку STL (см. http://www.sgi.com/tech/stl/sort.html или http://msdn.microsoft. com / en-us / library / ecdecxh1 (VS.80) .aspx ) или старый C qsort: http://en.wikipedia.org/wiki/Qsort_ (C_Standard_Library) . Я бы не советовал писать собственный алгоритм сортировки, если это не домашнее задание. Ваше сравнение зависит от технологии, которую вы хотите использовать, оно может выглядеть примерно так:

int CompareCustomerProfile(
   const CustomerProfile* pC1,
   const CustomerProfile* pC2)
{
 int result = strcmp(pC1->name, pC2->name);
 if (0 != result) return result; 

  result = strcmp(pC1->ID, pC2->ID);
  if (0 != result) return result;

  if (pC1->amountDue < pC2->amountDue) return -1;
 if (pC1->amountDue > pC2->amountDue) return 1;

  return 0
}

предполагается, что тип 'string' в вашем примере - это char *. Если вы используете Unicode или многобайтовые типы, то, очевидно, необходимо использовать соответствующее Unicode или многобайтовое сравнение. Then you would just call the algorithm, with your comparison function. Eg. using qsort:

qsort(c, Count, sizeof(CustomerProfile), CompareCustomerProfiler).

Now if this is a homework assignment, you shouldn't be asking here how to do it...

2
ответ дан 1 December 2019 в 00:14
поделиться

You can find a lot of sort implementations in C++ with creative googling.. The only difference is that instead of sorting numbers, you are sorting structs.

So wherever there is something like if(a[i] in the algorithm you will use, make a call like `if(isFirstCustomerLowerThanOther(a[i]

Now, create a function with the following structure:

bool isFirstCustuomerLowerThanOther(const Customer& firstCustomer, const Customer& secondCustomer)
{
 // Implement based on your key preferences
}

Even better, if you use C++ you can use the STL's sort algortihm (again, google for info and for how to pass an ordering to it.

1
ответ дан 1 December 2019 в 00:14
поделиться

Я предполагаю, что вы новичок в программировании или в C ++, поэтому вот что вы, вероятно, ищете:

#include <search.h> // for the qsort()

int
CompareByName( const void *elem1, const void *elem2 )
{
  return ((Customers*)elem1)->Name > ((Customers*)elem2)->Name? 1 : -1;
}

int
CompareByOrderAmount( const void *elem1, const void *elem2 )
{
  return ((Customers*)elem1)->OrderAmount > ((Customers*)elem2)->OrderAmount? 1 : -1;
}

void SortData( int SortItem, int count, Customers customers[] )
{
  switch (SortItem) {
  case 0:
    qsort(customers, count, sizeof(Customers), CompareByName);
    break;
  case 1:
    qsort(customers, count, sizeof(Customers), CompareByOrderAmount);
    break;
  // ...
  }
}

void test()
{
  Customers cust[10];

  cust[0].Name = "ten";
  cust[1].Name = "six";
  cust[2].Name = "five";
  SortData( 0, 3, cust );
  cout << cust[0].Name << endl;
  cout << cust[1].Name << endl;
  cout << cust[2].Name << endl;
}
0
ответ дан 1 December 2019 в 00:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: