Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print the number of elements of a list

I have the code below:

#include <iostream>
#include <list>
using namespace std;

class YTchannel{
public: 
    string name;
    string owner;
    int subs;
    list<string> video_title;
};

int main(){

    YTchannel ytc; 
    ytc.video_title={"A", "B", "C"};
    for(string videotitle: ytc.video_title){
        for(int i=1;i<=videotitle.size();i++){
            cout<<i<<videotitle<<endl;
            break;
        }
    }

I want to display the list of video titles with their respective number:
1A
2B
3C

But if I run the code, i’ll obtain:
1A
1B
1C

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a ‘break’ in your loop so you never increment the counter.

Additionally, in C++20 you can narrow the scope, by using the init statement in range-based loop.

#include <iostream>
#include <list>
using namespace std;

class YTchannel{
public: 
    string name;
    string owner;
    int subs;
    list<string> video_title;
};

int main(){

    YTchannel ytc; 
    ytc.video_title={"A", "B", "C"};
    int counter = 0; 
    for(string videotitle : ytc.video_title){
        cout<<++counter<<videotitle<<endl;
    }

    // C++20
   //YTchannel ytc; 
   //ytc.video_title={"A", "B", "C"};
   //for(int counter = 0; string videotitle : ytc.video_title){
   //   cout<<++counter<<videotitle<<endl;
   //}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading