quinta-feira, 8 de outubro de 2020

Container multiset - declarando e inicializando


O container multiset que pertence ao arquivo
de cabeçalho <set>, tem muitas semelhanças,
ao seu parente set, do qual já falamos um pouco.
Acreditamos que a única diferença esteja
no seu recurso de suportar chaves duplicadas
na sua interface, enquanto um set não suporta.
Um multiset também é associativo,
e ordenado ascendente, mas não elimina
elementos duplicados.
Podemos remover ou inserir novos elementos
no container, automaticamente ele se ajusta
a uma ordem restrita referenciada por sua chave.
Como em um set, não se permite alterações de valores,
isto foi definido por segurança para que a ordem
dos elementos não fossem corrompidas.
Um programador iniciante em C++ fica confuso
na escolha do melhor repositório para seu programa,
isto ocorre pela semelhança, entre eles,
alguns com poucas diferenças em suas funções básicas.
Certamente encontraremos a estrutura correta
e adequada para nossos programas funcionarem 
com perfeição e com performance satisfatórias.
Mesmo os containers do C++ serem bastante flexíveis,
aceitando variadas conversões, é de extrema importância
evitar estes procedimentos, popularmente
chamado de gambiarra ou improvisos por nós programadores.
Para este exemplo, declaramos um multiset e um set.
O multiset foi inicializado com várias strings
em forma de frase, no seu próprio corpo bem desordenadas,
e na primeira impressão a da esquerda que se refere
ao multisete já notamos as frases todas ordenadas,
mas com todas as repetições, que é típico do multiset,
não exclui valores duplicados, e na impressão da direita,
que se refere ao set percebemos que os valores
repetidos foram apagados e as frases ficaram também
ordenadas como era de se esperar.




//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <iterator>
#include <algorithm>
#include <set>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
    //SetBkColor ( Canvas -> Handle, RGB ( 255, 182, 193 ) );
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
    Canvas -> Font -> Size = 11;
    Canvas -> Font -> Name = "Arial";
    Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 350, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 390, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 350, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 12;
Label1 -> Font -> Name = "Arial";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
//Label1 -> Font -> Color = clBlack;
Label1 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Label1 -> Color = static_cast < TColor > ( RGB ( 255, 215, 0 ) );
Label1 -> Transparent = False;
Label1 -> Width = 240;
Label1 -> Height = 240;
Label1 -> Left = 40;
Label1 -> Top = 40;

Label2 -> Visible = true;
Label2 -> Font -> Size = 12;
Label2 -> Font -> Name = "Arial";
Label2 -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
//Label2 -> Font -> Color = clBlack;
Label2 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Label2 -> Color = static_cast < TColor > ( RGB ( 255, 255, 55 ) );
Label2 -> Transparent = False;
Label2 -> Width = 240;
Label2 -> Height = 240;
Label2 -> Left = 340;
Label2 -> Top = 40;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 255 ) );
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = static_cast < TColor > ( RGB ( 255, 0, 0 ) );
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 255, 0, 0 ) );
//SetBkColor ( Canvas -> Handle, RGB ( 218, 112, 214 ) );
Canvas -> TextOut ( 100, 10, "MULTISET - DECLARANDO E INICIALIZANDO" );
Informe ( Sender );
   }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
   Label_Manual ( Sender );
   String str_1;
   String str_2;

            std::multiset < String > mst = {
"  Goiaba vermelha, fruta boa  ",
"  Eu sabia fazer, mas esqueci ",
"  Fevereiro não tem carnaval  ",
"  Busque a paz e a siga       ",
"  Haverá paz no vale pra mim  ",
"  Cada louco com sua mania    ",
"  Amanhã será um novo dia     ",
"  Haverá paz no vale pra mim  ",
"  Goiaba vermelha, fruta boa  ",
"  Amanhã será um novo dia     ",
"  Eu sabia fazer, mas esqueci ",
"  Duvido que você irá desistir"};

for ( String val : mst ) {
   if ( val >= "  " )
str_1 += "\n";
str_1 += val;
}
Label1 -> Caption = str_1;

//Declarando um set para tipo String do C++ Builder
std::set < String > st;

//Copia os valores do multiset no set
for ( String val : mst ) {
st.insert ( val );
}

for ( String val : st ) {
   if ( val >= "  " )
str_2 += "\n";
str_2 += val;
}
Label2 -> Caption = str_2;


}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Buttons.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;
TLabel *Label2;

void __fastcall Informe ( TObject *Sender );
void __fastcall Label_Manual ( TObject *Sender );
void __fastcall FormPaint ( TObject *Sender );
void __fastcall FormShow(TObject *Sender);
private: // User declarations

public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Nenhum comentário:

Postar um comentário

Observação: somente um membro deste blog pode postar um comentário.