Вектор множеств в C ++
Предварительное условие: векторы в C ++ STL
Векторы известны как динамические массивы с возможностью автоматического изменения размера при вставке или удалении элемента, причем их хранение автоматически обрабатывается контейнером.
Наборы - это тип ассоциативных контейнеров, в которых каждый элемент должен быть уникальным, потому что значение элемента идентифицирует его. Значение элемента не может быть изменено после его добавления в набор, хотя можно удалить и добавить измененное значение этого элемента.
Вектор наборов может быть использован для разработки сложных и эффективных структур данных, в этой статье мы собираемся проверить один такой пример, где вектор наборов может быть очень полезен.
Синтаксис:
vector<set<datatype>> v ;
Вставка в вектор множеств
Элементы могут быть вставлены в вектор с помощью функции push_back () C ++ STL. Сначала вставьте элементы в набор с помощью insert (). Затем вставьте этот набор в вектор с помощью push_back ().
Below example demonstrates the insertion operation in a vector of sets:
C++
// C++ program to demonstrate the // insertion into a vector of sets #include <bits/stdc++.h> using namespace std; // Defining the number of sets // in the vector and number of // elements in each set #define ROW 4 #define COL 5 // Driver Code int main() { // Initialize vector of sets vector<set< int > > v; // Elements to insert // in column int num = 10; // Inserting elements // into vector for ( int i = 0; i < ROW; i++) { // Stores the column elements set< int > s; for ( int j = 0; j < COL; j++) { s.insert(num); num += 5; } // Push the set in the vector v.push_back(s); } // Display the vector of sets for ( int i = 0; i < v.size(); i++) { for ( auto x : v[i]) cout << x << " " ; cout << endl; } return 0; } |
10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105
Removal or Deletion in a Vector of Sets
Sets can be removed from the end of a vector of sets using the pop_back() function of C++ STL.
Below example demonstrates the removal of sets from the end of a vector of sets:
C++
// C++ program to demonstrate
// the removal of sets from
// the end of vector of sets
#include <bits/stdc++.h>
using
namespace
std;
// Defining the number of sets
// in the vector and number of
// elements in each set
#define ROW 4
#define COL 5
// Driver Code
int
main()
{
// Initialize the
// vector of sets
vector<set<
int
> > v;
// Elements to insert
// in column
int
num = 10;
// Inserting elements
// into vector
for
(
int
i = 0; i < ROW; i++) {
// Vector to store
// column elements
set<
int
> s;
for
(
int
j = 0; j < COL; j++) {
s.insert(num);
num += 5;
}
// Push the set
// into the vector
v.push_back(s);
}
// Display the vector of sets
// before removal of sets
cout <<
"Before Removal:"
<< endl;
for
(
int
i = 0; i < v.size(); i++) {
for
(
auto
x : v[i])
cout << x <<
" "
;
cout << endl;
}
// Remove sets from last
// index of the vector
v.pop_back();
v.pop_back();
// Display the vector of sets
// after removal of sets
cout << endl
<<
"After Removal:"
<< endl;
for
(
int
i = 0; i < v.size(); i++) {
for
(
auto
x : v[i])
cout << x <<
" "
;
cout << endl;
}
return
0;
}
Output:Before Removal: 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 After Removal: 10 15 20 25 30 35 40 45 50 55
The value of the element cannot be modified once it is added to the set, though it is possible to remove the value of that element. erase() function is used to remove a particular element from a particular set of a vector of sets.
Below example demonstrates the removal of a given set element from a particular set of a vector of sets:
C++
// C++ program to demonstrate
// the removal of sets from
// the end of vector of sets
#include <bits/stdc++.h>
using
namespace
std;
// Defining the number of sets
// in the vector and number of
// elements in each set
#define ROW 4
#define COL 5
// Driver Code
int
main()
{
// Initialize vector of sets
vector<set<
int
> > v;
// Elements to insert
// in column
int
num = 10;
// Inserting elements
// into vector
for
(
int
i = 0; i < ROW; i++) {
// Vector to store
// column elements
set<
int
> s;
for
(
int
j = 0; j < COL; j++) {
s.insert(num);
num += 5;
}
// Push the set
// into the vector
v.push_back(s);
}
// Display the vector of sets
// before removal of sets
cout <<
"Before Removal:"
<< endl;
for
(
int
i = 0;
i < v.size(); i++) {
for
(
auto
x : v[i])
cout << x <<
" "
;
cout << endl;
}
// Erase 70 from 3rd set
v[2].erase(70);
// Erase 55 from 2nd set
v[1].erase(55);
// Display the vector of sets
// after removal of sets
cout << endl
<<
"After Removal:"
<< endl;
for
(
int
i = 0; i < v.size(); i++) {
for
(
auto
x : v[i])
cout << x <<
" "
;
cout << endl;
}
return
0;
}
Output:Before Removal: 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 After Removal: 10 15 20 25 30 35 40 45 50 60 65 75 80 85 90 95 100 105
The following example demonstrates the use of vector of sets:
Given a string S, the task is to seperate the given string S into three different set of characters i.e., vowel, consonants, or a special character.
Below is the implementation of the above problem:
C++
// C++ program to implement vector of sets #include <bits/stdc++.h> using namespace std; // Function to print set // of different characters void separateChar(string s) { // Vector of set vector<set< char > > v(3); // Insert data in vector of set for ( int i = 0; i < s.length(); i++) { if (s[i] >= "a" && s[i] <= "z" ) { // Insert vowels if (s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" ) v[0].insert(s[i]); // Insert consonants else v[1].insert(s[i]); } // Insert special characters else v[2].insert(s[i]); } // Iterate over all the sets for ( int i = 0; i < 3; i++) { cout << "Elements of set " << i + 1 << " :" ; // Print elements of each set for ( auto it : v[i]) { cout << it << " " ; } cout << endl; } } // Driver Code int main() { string s = "geeks@for&geeks@" ; // Function Call separateChar(s); } |
Elements of set 1 :e o Elements of set 2 :f g k r s Elements of set 3 :& @