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"};
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
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:
using namespace std;
#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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With