Write a Playlist class with a const accessor returning const std::string& and a non-const accessor returning std::string&, and show both in use.
Solution
main.cpp
#include <iostream>
#include <string>
#include <vector>
class Playlist {
std::vector<std::string> songs_;
public:
void add(std::string s) { songs_.push_back(std::move(s)); }
std::string& operator[](std::size_t i) { return songs_[i]; } // editable
const std::string& operator[](std::size_t i) const { return songs_[i]; } // read-only
std::size_t size() const { return songs_.size(); }
};
void print(const Playlist& p) { // const object → const operator[] is used
for (std::size_t i = 0; i < p.size(); ++i) std::cout << i + 1 << ". " << p[i] << '\n';
}
int main() {
Playlist p;
p.add("Kesariya");
p.add("Tum Hi Ho");
p[1] += " (Acoustic)"; // modify through the returned reference
print(p);
return 0;
}
Output Verified by compiling and running
1. Kesariya
2. Tum Hi Ho (Acoustic)
The pair of overloads gives write access to non-const playlists and read-only access to const ones. add takes its parameter by value and moves it into the vector.
More References: lvalue and rvalue practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!