Issue regarding initializer_list
I recently tried using the new c++0x standard and I was wondering why the following code won't compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
#include <vector>
#include <string>
#include <initializer_list>
std::vector<int> *createvec(std::initializer_list<int> il){
std::vector<int> *pv = new std::vector<int>(il); // initialized the
//vector through the initializer list il
return pv;
}
void printvec(std::vector<int> *p){
for(auto it = p->begin(); it != p->end(); ++it){
std::cout<<*it<<std::endl;
}
delete p;
}
int main(){
std::vector<int> *thepointer = createvec({3,5,8,2});
printvec(thepointer);
thepointer = nullptr;
return 0;
}
| |
However when I removed the initializer_list argument and inserted the values manually within the function, the code works fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <vector>
#include <string>
std::vector<int> *createvec(){
std::vector<int> *pv = new std::vector<int>({4,3,7,1}); // manual insertion
return pv;
}
void printvec(std::vector<int> *p){
for(auto it = p->begin(); it != p->end(); ++it){
std::cout<<*it<<std::endl;
}
delete p;
}
int main(){
std::vector<int> *thepointer = createvec();
printvec(thepointer);
thepointer = nullptr;
return 0;
}
| |
Any ideas as to why this is the case?
My suggestion is: update your compiler.
Your first source code compiles without problems with Visual Studio 2013.
It also compiles fine on with modern GCC:
http://ideone.com/eXQvmw
Also, C++0x has since evolved into C++11.
Topic archived. No new replies allowed.