incognito
incognito

Reputation: 5

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

Upvotes: 0

Views: 162

Answers (3)

DividedByZero
DividedByZero

Reputation: 4391

You're printing the string ("A", "B", or "C")'s length - not the list's. You want:

    ytc.video_title={"A", "B", "C"};
    auto it = ytc.begin()
    for(size_t i =0; i < ytc.size(); ++i){
        cout<<i<<*it++<<endl;
    }

However what you probably really want is:

#include <iostream>
#include <vector>
#include <algorithm>

// Include the headers for std::string
#include <string>

// Don't use 'using namespace std'

// Structs are all public by default, so they're a better choice than a class here
struct YTchannel{
    std::string name;
    std::string owner;
    int subs;
    // Vector is a better choice than list unless you know why it isn't
    std::vector<string> video_title;
};

int main(){
    YTchannel ytc; 
    ytc.video_title={"A", "B", "C"};

    for(auto it = ytc.begin(); it != ytc.end(); ++it){
        std::cout << std::distance(ytc.begin(), it) << videotitle << std::endl;
}

Upvotes: 0

bielu000
bielu000

Reputation: 2241

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;
   //}
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

The frist loop:

for(string videotitle: ytc.video_title)

iterates over all the strings in the list.

The second loop:

for(int i=1;i<=videotitle.size();i++)

iterates over all characters in the current string. And in that loop you print the whole string each iteration.

The simple solution is to keep a separate counter that you increase in the one single first loop:

unsigned counter = 1;
for (auto const& title : yts.video_titles)
{
    std::cout << counter++ << ' ' << title << '\n';
}

Upvotes: 4

Related Questions