2013-04-16 49 views
1

看起来属性test aisbn正在成功存储调用setCode(),setDigit()的数据。但麻烦开始出现问题,而我试图将这些值存储到list<test> simul未能将值存储到列表中

list属性setDigit()但代码后需要数字的值。我怎样才能把代码和数字放到列表属性中?我看不出问题在哪里。代码:

#include <iostream> 
#include <stdlib.h> 
#include <string> 
#include <fstream> 
#include <list> 
using namespace std; 

class test 
{ 
    private: 
     string code; 
     int digit; 

    public: 
     //constructor 
     test(): code(""), digit(0) { } 

     //copy constructor 
     test(const test &other): 
     digit(other.digit) 
     { 
      for(unsigned int i=0; i < code.length(); i++) 
       code[i] = other.code[i]; 
     } 

     //set up the private values 
     void setCode(const string &temp, const int num); 
     void setCode(const string &temp); 
     void setDigit(const int &num); 


     //return the value of the pointer character 
     const string &getCode() const; 
     const unsigned int getDigit() const; 
}; 

const string& test::getCode() const 
{ 
    return code; 
} 
const unsigned int test::getDigit() const 
{ 
    return digit; 
} 
void test::setCode(const string &temp, const int num) 
{ 
    if((int)code.size() <= num) 
    { 
     code.resize(num+1); 
    } 
    code[num] = temp[num]; 
} 
void test::setCode(const string &temp) 
{ 
    code = temp; 
} 
void test::setDigit(const int &num) 
{ 
    digit = num; 
} 


int main() 
{ 
    const string contents = "dfskr-123"; 

    test aisbn; 
    list<test> simul; 
    list<test>::iterator testitr; 
    testitr = simul.begin(); 
    int count = 0; 

    cout << contents << '\n'; 
    for(int i=0; i < (int)contents.length(); i++) 
    { 
     aisbn.setCode(contents); 
     aisbn.setDigit(count+1); 
     simul.push_back(aisbn); 
     count++; 
    } 
    cout << contents << '\n'; 

    /*for(; testitr !=simul.end(); simul++) 
    { 
     cout << testitr->getCode() << "\n"; 
    }*/ 

} 

回答

0

它看起来像您有您的for循环的问题,您需要修改for循环像这样:

for(testitr = simul.begin(); testitr !=simul.end(); testitr++) 
    ^^^^^^^^^^^^^^^^^^^^^^^       ^^^^^^^^^ 

虽然,push_back不会为std::list我认为无效的迭代器设置您正在使用它的迭代器更具可读性。根据您的回应则还需要修改copy constructor

test(const test &other): code(other.code), digit(other.digit) {} 
         ^^^^^^^^^^^^^^^^ 
+0

忘记for循环。我想知道的是,simul.push_back(aisbn)只取得setDigit()中数字的值。你可以看看到用于代码(INT I = 0;我<(int)的contents.length();我++) \t \t { \t \t \t aisbn.setCode(内容); \t \t \t aisbn.setDigit(count + 1); \t \t \t simul.push_back(aisbn); \t \t \t count ++; \t \t} – user2282596

+0

@ user2282596修改答案 –

+0

很多thx。问题解决了 – user2282596

0

如何使用vector

std::vector<test> simul; 

for(int i=0; i < (int)contents.length(); i++) 
    { 
     aisbn.setCode(contents); 
     aisbn.setDigit(count+1); 
     simul.push_back(aisbn); 
     count++; 
    } 

迭代器,指针和相关的容器引用无效。否则,只有最后一个迭代器失效。

+0

我应该尽早使用vector。使用列表是强制性的:) – user2282596