C ++ 11 string list initialization
I was trying to initialize a list of strings in C ++ 11 using the following code and it fails for various reasons. The error says I need to use a 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 -
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"};
source to share
List initializers are only available in C ++ 11. To use C ++ 11, you probably need to pass a flag to the compiler. For GCC and Clang, this is -std=c++11
.
It also std::list
does not provide an index operator. You can either use std::vector
as in the other answer, or use a loop to iterate over the list.
A few more tips:
- never do
using namespace std;
- free space
#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';
}
source to share
The biggest problem here is that you are using lists. There are doubly linked lists in C ++ lists, so [] doesn't make any sense. You should use vectors instead.
I would try:
#include<string>
#include<vector>
#include<iostream>
using namespace std;
int main() {
string s = "Mark";
vector<string> l = {"name of the guy"," is Mark"};
cout<<s<<endl;
for (int i=0;i<l.size();i++) {
cout<<l[i]<<endl;
}
return 0;
}
instead
EDIT: as others have pointed out, make sure you compile with C ++ 11 and not C ++ 98
source to share