-4

I'm new to c++ and recently shifted from python. Can anyone explain me what should be the actual code in c++, if we want to print items of a list in for loop. For example: in python. We do something like.

sample_list = ['you', 'are','awesome']
for i in sample_list:
    print(i)

In C++ its something like.

for(initialisation, condition, updation )
{ 
Your code
}

But there is no update We just want to get items from a list.

How can I do same in C++?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Rajeev R S
  • 25
  • 3
  • You can iterate through a vector using the index but maybe you want a range based for loop. See the example at the bottom: [https://en.cppreference.com/w/cpp/language/range-for](https://en.cppreference.com/w/cpp/language/range-for) – drescherjm Feb 08 '22 at 14:25
  • I want a for loop. Which print all the values of a list until last item comes. – Rajeev R S Feb 08 '22 at 14:26
  • 6
    `for i in sample_list:` -> `for(const auto &i : sample_list)` – justANewb stands with Ukraine Feb 08 '22 at 14:26
  • Where is your `C++` code? Do you already have a collection? Have you looked up the different `for` loops in `C++`? – quamrana Feb 08 '22 at 14:27
  • 2
    *For example: in python. We do something like.* -- What Python does is really irrelevant. You are now coding in C++. Even your comment that you want a "for loop" is a bad sign that you are attempting to use Python as a model in writing C++ code. Don't do that. – PaulMcKenzie Feb 08 '22 at 14:27
  • 2
    If you want to learn C++ then please invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Feb 08 '22 at 14:27

3 Answers3

1
for(int i = 0; i < sample_list.size(); i++){
    cout << sample_list[i] << "\n";
}

or

for(auto i : sample_list) {
    cout << i << "\n";
}
1

You can use the form for(:) to iterate over every list element.

#include <iostream>
#include <string>
#include <vector>

int main()
{   
    std::vector<std::string> sample_list{"you", "are", "awesome"};

    for (auto item : sample_list)
        std::cout << item << std::endl;
    
    return 0;
}
Matt
  • 721
  • 9
  • 26
0

It looks like you're looking for a string array made with

#include <string>

int main() {
  std::string array[];
}

Now all you need to do is run a for loop that prints the Ith member of the array with

#include <iostream>
#include <string>

int main() {
  std::string array[5];
  for(int i; i<5; i++) {
    std::cout << array[i] << std::endl;
  }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578