Introdução
Neste laboratório, aprenderemos como usar o método lower_bound() no Vector STL em C++. A implementação prática deste método será demonstrada no laboratório.
Neste laboratório, aprenderemos como usar o método lower_bound() no Vector STL em C++. A implementação prática deste método será demonstrada no laboratório.
O que são Vectors?
Vectors são arrays dinâmicos com a capacidade adicional de redimensionarem-se e ajustarem automaticamente seu tamanho quando inserimos ou deletamos elementos. Vectors oferecem mais flexibilidade em comparação com arrays estáticos normais.
Nesta etapa, criaremos um vector vazio e inseriremos alguns elementos nele. Observe que, como vectors são dinâmicos, não precisamos especificar o tamanho do vector antes de inserir elementos.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// create an empty vector
vector<int> v;
// insert elements into the vector
v.push_back(10);
v.push_back(12);
v.push_back(35);
v.push_back(65);
v.push_back(21);
v.push_back(90);
}
Nesta etapa, ordenaremos os elementos do vector em ordem crescente usando a função sort() da biblioteca <algorithm>.
// sorting the vector in ascending order
sort(v.begin(), v.end());
Agora, usaremos o método lower_bound() para encontrar um iterador que aponta para o primeiro elemento que possui um valor não menor que o valor fornecido.
// define the iterator low
vector<int>::iterator low;
// use lower_bound to find the first element that's not less than 35
low = lower_bound(v.begin(), v.end(), 35);
Nesta etapa, imprimiremos o índice do limite inferior (lower bound) de 35 e algumas notas sobre o resultado.
// print the index of the lower bound of 35
cout << "\nThe index (starting from 0) of the lower_bound of 35 is: " << (low - v.begin()) << '\n';
// print some notes
cout << "\nNote that as per the definition, it also considers the number itself.\n\n";
Aqui está o código completo para o arquivo main.cpp:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// create an empty vector
vector<int> v;
// insert elements into the vector
v.push_back(10);
v.push_back(12);
v.push_back(35);
v.push_back(65);
v.push_back(21);
v.push_back(90);
// print the elements of the vector
cout << "The elements of the Vector are: ";
for (int i : v)
{
cout << i << " ";
}
// sorting the vector in ascending order
sort(v.begin(), v.end());
// print the sorted vector
cout << "\n\nThe elements of the Vector after Sorting are: ";
for (int i : v)
{
cout << i << " ";
}
// define the iterator low
vector<int>::iterator low;
// use lower_bound to find the first element that's not less than 35
low = lower_bound(v.begin(), v.end(), 35);
// print the index of the lower bound of 35
cout << "\n\nThe index (starting from 0) of the lower_bound of 35 is: " << (low - v.begin()) << '\n';
// print some notes
cout << "\nNote that as per the definition, it also considers the number itself.\n\n";
return 0;
}
Para executar o programa, abra uma janela de terminal e navegue até o diretório que contém o arquivo main.cpp. Use os seguintes comandos para compilar e executar o programa:
g++ main.cpp -o main && ./main
Isso deve compilar e executar o programa, e você deverá ver a seguinte saída:
The elements of the Vector are: 10 12 35 65 21 90
The elements of the Vector after Sorting are: 10 12 21 35 65 90
The index (starting from 0) of the lower_bound of 35 is: 3
Note that as per the definition, it also considers the number itself.
Parabéns! Neste laboratório, você aprendeu sobre o método lower_bound() na STL (Standard Template Library) Vector em C++, e viu sua implementação usando vetores. Com essas habilidades, você pode criar, ordenar e pesquisar elementos em vetores com precisão. Ótimo trabalho!