The Wayback Machine - https://web.archive.org/web/20240823022713/https://www.geeksforgeeks.org/stl-ropes-in-c/
Open In App

STL Ropes in C++

Last Updated : 03 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
59.72%
7.8K

Ropes are scalable string implementation. They are designed for efficient operation that involves the string as a whole. Operations such as assignment, concatenation, and sub-string take time that is nearly independent of the length of the string.

A rope is a binary tree where each leaf (end node) holds a string and a length (also known as a “weight”), and each node further up the tree holds the sum of the lengths of all the leaves in its left subtree. A node with two children thus divides the whole string into two parts: the left sub-tree stores the first part of the string, the right subtree stores the second part of the string, and a node’s weight is the length of the first part.

For rope operations, the strings stored in nodes are assumed to be constant immutable objects in the typical non-destructive case, allowing for some copy-on-write behavior. Leaf nodes are usually implemented as basic fixed-length strings with a reference count attached for deallocation when no longer needed, although other garbage collection methods can be used as well.

Note: The rope class and rope header are SGI extensions; they are not part of the C++ standard library.

Declaration:
Ropes are defined in the same way as vectors as “vector<int>”. But for character ropes, we can use crope as “rope<char>”.

Below is the program for the same:

Program 1:

C++




// C++ program to illustrate the use
// of ropes using Rope header file
#include <ext/rope>
#include <iostream>
 
// SGI extension
using namespace __gnu_cxx;
 
using namespace std;
 
// Driver Code
int main()
{
    // rope<char> r = "abcdef"
    crope r = "abcdef";
 
    cout << r << "\n";
 
    return 0;
}


 
 

Output: 

abcdef

 

 

Operations allowed on Rope:

 

  • push_back(): This function is used to input a character at the end of the rope. Time Complexity: O(log N).
  • pop_back(): Introduced from C++11(for strings), this function is used to delete the last character from the rope. Time Complexity: O(log N).
  • insert(int x, crope r1): Inserts the contents of r1 before the xth element. Time Complexity: For Best Case: O(log N) and For Worst Case: O(N).
  • erase(int x, int l): Erases l elements, starting with the xth element. Time Complexity: O(log N).
  • substr(int x, int l): Returns a new rope whose elements are the l characters starting at the position x. Time Complexity: O(log N).
  • replace(int x, int l, crope r1): Replaces the l elements beginning with the xth element with the elements in r1. Time Complexity: O(log N).
  • concatenate(+): concatenate two ropes using the ‘+’ symbol. Time Complexity: O(1).

 

Below is the program for the same:

 

Program 2:

 

C++




// C++ program to illustrate the use
// of ropes using Rope header file
#include <ext/rope>
#include <iostream>
 
// SGI extension
using namespace __gnu_cxx;
using namespace std;
 
// Driver Code
int main()
{
    // rope<char> r = "abcdef"
    crope r = "geeksforgeeks";
 
    cout << "Initial rope: "
         << r << endl;
 
    // 'g' is added at the
    // end of the rope
    r.push_back('g');
    r.push_back('f');
    r.push_back('g');
 
    cout << "Rope after pushing f: "
         << r << endl;
 
    int pos = 2;
 
    // gfg will be inserted
    // before position 2
    r.insert(pos - 1, "gfg");
 
    cout << "Rope after inserting "
         << "gfg at position 2: " << r
         << endl;
 
    // gfg will be deleted
    r.erase(pos - 1, 3);
 
    cout << "Rope after removing gfg"
         << " inserted just before: "
         << r << endl;
 
    // Replace "ee" with "00"
    r.replace(pos - 1, 2, "00");
 
    cout << "Rope after replacing "
         << "characters: " << r
         << endl;
 
    // Slice the rope
    crope r1 = r.substr(pos - 1, 2);
 
    cout << "Subrope at position 2: "
         << r << endl;
 
    // Removes the last element
    r.pop_back();
    r.pop_back();
    r.pop_back();
 
    cout << "Final rope after popping"
         << " out 3 elements: " << r;
 
    return 0;
}


Output

Initial rope: geeksforgeeks
Rope after pushing f: geeksforgeeksgfg
Rope after inserting gfg at position 2: ggfgeeksforgeeksgfg
Rope after removing gfg inserted just before: geeksforgeeksgfg
Rope after replacing characters: g00ksforgeeksgfg
Subrope at position 2: g00ksforgeeksgfg
Final rope after popping out 3 elements: g00ksforgeeks

 
 

 

Capacity Functions:

 

  • size(): Returns the length of the rope.
  • max_size(): Size of longest rope guaranteed to be representable.

 

Below is the program for the same:

 

Program 3:

 

C++




// C++ program to illustrate the use
// of ropes using Rope header file
#include <ext/rope>
#include <iostream>
 
// SGI extension
using namespace __gnu_cxx;
using namespace std;
 
// Driver Code
int main()
{
    // rope<char> r = "abcdef"
    crope r = "abcdef";
 
    cout << r.size() << endl;
    cout << r.max_size() << endl;
    return 0;
}


 
 

Output: 

6
1836311902

 

 

Iterators:

 

  • mutable_begin(): Returns an iterator pointing to the beginning of the rope.
  • mutable_end(): Returns an iterator pointing to the end of the rope.

 

Below is the program for the same:

 

Program 4:

 

C++




// C++ program to illustrate the use
// of ropes using Rope header file
#include <ext/rope>
#include <iostream>
 
// SGI extension
using namespace __gnu_cxx;
using namespace std;
 
// Driver Code
int main()
{
    // rope<char> r = "abcdef"
    crope r = "abcdef";
 
    rope<char>::iterator it;
    for (it = r.mutable_begin();
         it != r.mutable_end(); it++) {
 
        // Print the value
        cout << char((*it) + 2)
             << "";
    }
 
    return 0;
}


 
 

Output: 

cdefgh

 

 



Similar Reads

Maximum length of all possible K equal length ropes generated by cutting N ropes
Given an array arr[] consisting of N positive integers representing the lengths of N ropes and a positive integer K, the task is to find the maximum length of the rope that has a frequency of at least K by cutting any ropes in any number of pieces. Examples: Input: arr[] = {5, 2, 7, 4, 9}, K = 5Output: 4Explanation:Below are the possible cutting of
8 min read
Maximize ropes of consecutive length possible by connecting given ropes
Given an array A[ ] of size N where each array element represents the length of a rope, the task is to find the number of ropes of consecutive length that can be created by connecting given ropes starting from length 1. Examples : Input: N = 5, A[ ] = {1, 2, 7, 1, 1} Output: 5 Explanation: Length | Ropes 1 | [1] 2 | [1, 1] 3 | [1, 2] 4 | [1, 2, 1]
6 min read
N consecutive ropes problem
Given N ropes, each rope has a length associated with it. At a time, only two consecutive small ropes tied at end form a large rope and cost of forming sum of their length. Find the minimum cost when all ropes are tied to form a single rope. Examples: Input: arr[] = {7, 6, 8, 6, 1, 1} Output: 68 {7, 6, 8, 6, 1, 1} - {7, 6, 8, 6, 2}, cost = 2 {7, 6,
9 min read
Number of ways to use all the K ropes
Given two walls A, B with M, and N hooks respectively. You are also given K ropes. By using one rope you can connect one hook on wall A with another hook on wall B. One hook can connect with only one rope. Find the number of different ways you can use all the K ropes.Two ways that use the exact same set of hooks from wall A and wall B are considere
7 min read
Ropes left after every removal of smallest
Given an array of an integer of size, N. Array contains N ropes of length Ropes[i]. You have to perform a cut operation on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut. Perform operations till the length of each rope becomes zero. Note: IF no ropes left after a single o
8 min read
Ropes Data Structure (Fast String Concatenation)
One of the most common operations on strings is appending or concatenation. Appending to the end of a string when the string is stored in the traditional manner (i.e. an array of characters) would take a minimum of O(n) time (where n is the length of the original string). We can reduce time taken by append using Ropes Data Structure. Ropes Data Str
15+ min read
Connect n ropes with minimum cost
Given are N ropes of different lengths, the task is to connect these ropes into one rope with minimum cost, such that the cost to connect two ropes is equal to the sum of their lengths. Examples: Input: arr[] = {4,3,2,6} , N = 4Output: 29Explanation:  First, connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6, and 5. Now conne
6 min read
Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators. Examples: vector &lt;in
3 min read
Sort on the basis of number of factors using STL
Given an array of positive integers. Sort the given array in decreasing order of a number of factors of each element, i.e., an element having the highest number of factors should be the first to be displayed and the number having the least number of factors should be the last one. Two elements with an equal number of factors should be in the same o
7 min read
Default values in a Map in C++ STL
Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map&lt;int,int&gt; mpp; mpp[1]; ) if the key is
2 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Count the number of 1's and 0's in a binary array using STL in C++ ?
Given a binary array, the task is to count the number of 1's and 0's in this array using STL in C++. Examples: Input: arr[] = {1, 0, 0, 1, 0, 0, 1} Output: 1's = 3, 0's = 4 Input: arr[] = {1, 1, 1, 1, 0, 0, 1} Output: 1's = 5, 0's = 2 Approach: We can count the same using count_if() function present in the STL of C++. Syntax: count_if(lower_bound,
1 min read
push_back() vs emplace_back() in C++ STL Vectors
In C++, vectors are dynamic arrays, that can grow or shrink and their storage is handled by the container itself. There are two ways of inserting an element in a vector. They are push_back() and emplace_back(). In this article, we will discuss the difference between them. push_back(): This method is used to insert elements in a vector from the end
5 min read
Count smaller elements on right side using Set in C++ STL
Write a function to count the number of smaller elements on the right of each element in an array. Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains the count of smaller elements on right side of element arr[i] in the array. Examples: Input : arr[] = {12, 1, 2, 3, 0, 11, 4}
4 min read
set vs unordered_set in C++ STL
Differences : | set | unordered_set --------------------------------------------------------- Ordering | increasing order | no ordering | (by default) | Implementation | Self balancing BST | Hash Table | like Red-Black Tree | search time | log(n) | O(1) -&gt; Average | | O(n) -&gt; Worst Case Insertion time | log(n) + Rebalance | Same as search Del
4 min read
deque assign() function in C++ STL
The deque::assign() is a built-in function in C++ STL which is used to assign values to the same or different deque container. On being called more than once in the same program, the function destroys the values of the previous elements and re-assigns new set of elements to the container. Syntax: deque_name.assign(size, val) Parameters: The functio
2 min read
count_if() in C++ STL
count_if() function returns the number of elements in a range that satisfy the condition. Syntax: template &lt;class InputT, class UnaryPredicate&gt; typename iterator_traits &lt;InputT&gt; :: difference_type count_if(InputT first, InputT last, UnaryPredicate p); Examples: Input: 0 1 2 3 4 5 6 7 8 9 Output: Total no of even numbers is: 5 Input: 2 3
2 min read
bitset count() in C++ STL
bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Syntax: int count() Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits. It returns the total number of ones or the number of set bits in the binary representation of the number
2 min read
bitset test() in C++ STL
bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not. Syntax: bitset_name.test(index) Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not. Return Value: The function returns a boolean value. It returns true if the bit
2 min read
set::rbegin() and set::rend() in C++ STL
set::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: reverse_iterator set_name.rbegin() Parameters: The function does not take any parameter. Return value: The function returns a reverse iterator pointing to the last element in the container. Program to demonstrate t
2 min read
array::crbegin() and array::crend() in C++ STL
array::crbegin() is a built-in function in C++ STL which returns a constant reverse iterator pointing to the last element in the container. Syntax:array_name.crbegin()Parameters: The function does not accepts any parameter. Return value: The function returns a reverse iterator pointing to the last element in the container. Program to demonstrate th
2 min read
multimap clear() function in C++ STL
The multimap clear() function is an inbuilt function in C++ STL which is used to remove all elements from the multimap container (which are destroyed), leaving the container with a size of 0. Syntax : mymultimap_name.clear() Parameters: This function does not take any arguments. Return Value: This function does not returns anything. The return type
2 min read
Prime numbers in a given range using STL | Set 2
Generate all prime numbers between two given numbers. The task is to print prime numbers in that range. The Sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n where n is smaller than 10 million or so. Examples: Input : start = 50 end = 100 Output : 53 59 61 67 71 73 79 83 89 97 Input : start = 900 end = 1000 O
8 min read
Relational Operators on STL Array in C++
The article illustrates the working of the different relational operator on the array STL. The equality comparison ( == ) is performed by comparing the elements sequentially using operator ( == ), stopping at the first mismatch. The less-than comparison ( &lt; ) or greater-than comparison ( &gt; ) behaves as if using algorithm lexicographical_compa
3 min read
Finding Floor and Ceil of a Sorted Array using C++ STL
Given a sorted array, the task is to find the floor and ceil of given numbers using STL.Examples: Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32}, values[] = { 1, 3, 5, 7, 20, 24 } Output: Floor Values: 1 2 4 7 12 23 Ceil values: 1 4 7 7 23 30 In case of floor(): lower_bound() method os STL will be used to find the lower bound. This returns an iter
3 min read
map key_comp() in C++ STL
The std::map::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator ‘&lt;&#039;.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the fi
2 min read
multiset key_comp() function in C++ STL
The std::multiset::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator ‘&lt;&#039;.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if
2 min read
Print Minimum of all Subarrays using set in C++ STL
Given an array of size N and an integer K, find the minimum for each and every contiguous subarray of size K. Examples: Input : arr[] = {5, 3, 4, 1, 1}, K = 3 Output : 3 1 1 Input : arr[] = {1, 2, 3, 4, 1, 6, 7, 8, 2, 1}, K = 4 Output : 1 1 1 1 1 2 1 Prerequisite: Sliding Window Technique Set in C++ STL Set performs insertion and removal operation
3 min read
multiset erase() in C++ STL
Prerequisite : multiset The multiset::erase() is the STL function in C++ removes the specified element from multiset. There are three versions of this method. These are: Syntax: void erase (iterator position_of_iterator); Parameters: This method accepts following parameters: position_of_iterator: It refers to the position of the specific element to
4 min read
Finding Median of unsorted Array in linear time using C++ STL
Given an unsorted array arr[] having N elements, the task is to find out the median of the array in linear time complexity. Examples: Input: N = 5, arr[] = {4, 1, 2, 6, 5} Output: 4 Explanation: Since N = 5, which is odd, therefore the median is the 3rd element in the sorted array. The 3rd element in the sorted arr[] is 4. Hence the median is 4. In
3 min read
three90RightbarBannerImg