Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing list of strings in c++11

Tags:

c++

list

I was trying to initialize a list of strings in c++11 using the following code, and its failing with various reasons. The error says that I need to use constructor to initialize the list, should I use something like list<string> s = new list<string> [size] ? What am I missing here?

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

int main() {
      string s = "Mark";
      list<string> l  {"name of the guy"," is Mark"};
      cout<<s<<endl;
      int size = sizeof(l)/sizeof(l[0]);
      for (int i=0;i<size;i++) {
             cout<<l[i]<<endl;
      }
      return 0;
 }

I/O is

 strtest.cpp:8:47: error: in C++98 ‘l’ must be initialized by constructor, not 
 by ‘{...}’
 list<string> l  {"name of the guy"," is Mark"};
like image 241
Aparna Chaganti Avatar asked Jun 03 '17 05:06

Aparna Chaganti


2 Answers

You are using a compiler of c++98 instead of c++11.using this if you are using gcc

g++ -std=c++11 -o strtest strtest.cpp

you can replace c++11 with gnu++11

like image 111
K.Juce Avatar answered Oct 19 '22 11:10

K.Juce


List initializers are only available in C++11. To use C++11 you probably have to pass a flag to the compiler. For GCC and Clang this is -std=c++11.

Also, std::list does not provide a subscript operator. You could either use a std::vector as in the other answer or you use a range-based for loop to iterate over the list.

Some more hints:

  • never do using namespace std;
  • whitespace is free
#include <string>
#include <list>
#include <iostream>

int main() {
  std::string s = "Mark";
  std::list<std::string> l {"name of the guy"," is Mark"};

  for (auto const& n : l)
    std::cout << n << '\n';
}
like image 10
Henri Menke Avatar answered Oct 19 '22 10:10

Henri Menke