2015-09-26 95 views
-2

行“list listObject;”是说不允许char和listObject不能识别。有人能给我一个线索,说我做错了什么吗? 谢谢创建矢量方法

char list; 
vector<char> v(20); 
list<char> listObject; 
int i; 

for (i = 0; i < 20; i++) 
    v[i] = 'A' + i; 

cout << "Original contents of vector:\n"; 
for (i = 0; i < v.size(); i++) 
    cout << v[i] << " "; 
cout << "\n\n"; 

char str[] = "-TEST MESSAGE-"; 
for (i = 0; str[i]; i++) 
    listObject.push_back(str[i]); 

copy(listObject.begin(), listObject.end(), v.begin()); 

// display result 
cout << "Contents of vector after copy:\n"; 
for (i = 0; i < v.size(); i++) 
    cout << v[i] << " "; 
+3

你定义一个名为'list'一个'char',然后尝试定义类型'list'的对象。 – owacoder

+0

(除非你拿出'using namespace std;'你显然有某个地方) –

+0

这个矢量方法在哪里创建? – juanchopanza

回答

0

的第一点,作为owacodes曾表示,你试图定义一个名为列表中的局部变量,它与容器列表的名称冲突。

作为第二点:我做了一个可编译的例子,您可能会从中获益。

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <list> 

int main() 
{ 
    std::vector<char> v(20); 
    // use iota for the assignment, it does what you want 
    std::iota(v.begin(), v.end(), 'A'); 

    std::cout << "Original contents of vector:\n"; 
    for(auto n: v) std::cout << n << ' '; 
    std::cout << std::endl; 

    // use a std::string instaed of char[], it is easier to use and less error prone 
    std::string str("-TEST MESSAGE-"); 
    std::list<char> listObject; 
    listObject.insert(listObject.begin(),str.begin(),str.end()); 

    std::copy(listObject.begin(), listObject.end(), v.begin()); 
    // be careful, v is not resized (str will be truncated with a longer message) 

    std::cout << "new contents of vector:\n"; 
    for(auto n: v) std::cout << n << ' '; 
    std::cout << std::endl; 
} 

输出:

Original contents of vector: 
A B C D E F G H I J K L M N O P Q R S T 
new contents of vector: 
- T E S T M E S S A G E - O P Q R S T