2011-09-04 3 views
0

LinkedList의 생성자를 정수 배열로 초기화하려고 시도합니다.LinkedList가 배열을받을 생성자 C++

프로그램은 linked (array)를 호출합니다. 배열 내의 모든 값을 linkedlist에 추가합니다.

LinkedList::LinkedList(int array[]) 
{ 
    headPtr->setData(array[0]); //setData method stores the integer at position 0 inside headPtr 

    Node *currentPtr = headPtr; 

    for (int i = 0; i < array.length(); ++i) //for loop to add the integers to the next node 
    { 
     currentPtr->setNext(new Node(array[i])); //creates a new node with the integer value of array position i 
    } 
} 

문제는 (자바에서 오는)이 사항 Array.length 내가 배열의 길이가이 방법을 얻을 수 있다고 생각하지 않는다?

+6

재 : "자바에서 오는"- ** 정지 ** A [좋은 입문 C++ 책 (http://stackoverflow.com/questions/388242/the-definitive-c-book-을 선택하십시오. guide-and-list)를 읽고 그것을 통해 올바른 현대 C++를 배웁니다. C++은 Java가 아닙니다. C++로 프로그래밍 할 때 자바의 관점에서 생각하면 악몽 일뿐입니다. –

+2

C- 배열의 길이를 얻을 수 없습니다 (C- 문자열과 같이 끝나지 않는 한). 예를 들어'std :: vector '에서 얻을 수 있습니다. –

+0

@WTP : C-Array의 길이를 얻을 수 있습니다. 그러나 배열이 포인터로 감쇄 된 경우 길이를 얻을 수 없습니다. OP는 후자의 상황에 직면 해있다. – Nawaz

답변

0

은 단지 중요하지만 동시에 자바에 대해 알고있는 것을 잊지하려고, 좋은 입문 C++ 책을 얻을 앞에서 뒤로 읽어 중요 동안 C++에서 모드 아니다 말했다 . 그들은 원격으로 유사하지 않습니다. 당신이 vector를 사용하지 않을 경우

// put this with the other includes for your file 
#include <vector> 

LinkedList::LinkedList(const std::vector<int>& array) 
{ 
    headPtr->setData(array[0]); //setData method stores the integer at position 0 inside headPtr 

    Node *currentPtr = headPtr; 

    for (int i = 0; i < array.size(); ++i) //for loop to add the integers to the next node 
    { 
     currentPtr->setNext(new Node(array[i])); //creates a new node with the integer value of array position i 
    } 
} 

, 당신은 배열의 크기에 전달해야한다 : 문제에 대한 지금

, std::vector를 사용하고 size 방법을 사용하여 해결 될 수있다 함수가 :

LinkedList::LinkedList(int array[], int arrlen) 
{ 
    headPtr->setData(array[0]); //setData method stores the integer at position 0 inside headPtr 

    Node *currentPtr = headPtr; 

    for (int i = 0; i < arrlen; ++i) //for loop to add the integers to the next node 
    { 
     currentPtr->setNext(new Node(array[i])); //creates a new node with the integer value of array position i 
    } 
} 

그러나이 vector 버전을 사용하는 것이 좋습니다.

+0

고마워, 내가 읽고있는 책이 내가 지금 읽고있는 자습서 운동이야, 그들의 예제는 조금 다르다,해야 할 수도 있습니다 서로 다른 두 권의 책을 읽으십시오. P 나는 제안한 내용을 벡터에 추가 한 것처럼 보이지만 경고가 있습니다. 부호가있는 정수 표현과 부호가없는 정수 표현을 비교할 수 있습니다. 부호가있는 부호가없는 것이 무엇을 의미하는지 확실하지 않습니다. – Cheeseman

+0

@Cheeseman은 음수가 될 수있는 수와 음수가 될 수없는 수를 비교한다는 것을 의미합니다. 음수가 아닌 숫자는 음수 값으로 예약 된 공간을 낭비하지 않기 때문에 양수 값을 높게 유지할 수 있습니다. 즉, 특정 크기가되면 _unsigned_ 값에 1을 더하면 다음으로 높은 값을 갖게되며 _signed_ 값에 1을 추가하면 정의되지 않은 동작이됩니다. 'vector :: size'는'unsigned int'를 반환합니다. 오류를 수정하려면 for (unsigned int i = 0; i

+0

아, 감사합니다, 세스 :) 아, 그래서 그것을 호출하려면, LinkedList list2 (arr); 괜찮을거야? – Cheeseman

3

난 당신이 반복자 관용구를 사용하는 것이 좋습니다 등과 같은 생성자에게 템플릿 생성자를 만들 것 :

class LinkedList 
{ 
    //... 
    public: 
    template<typename FwdIterator> 
    LinkedList(FwdIterator begin, FwdIterator end) 
    { 
     for (;begin != end; ++begin) 
     { 
      //treat begin as pointer, and *begin as dereferenced object 
     } 
    } 
    //... 
}; 

그리고 당신은로 사용할 수 있습니다 :

int arr[] = {1,2,3,4,5,6,7,8,9,10}; 

LinkedList lnklist(arr, arr+10); 

뿐만 아니라. 당신이 std::vector<int>를 한 경우에, 당신은 또한, 링크 된 목록을 구성하는 데 사용할 수 있습니다 :

std::vector<int> v; 
//.. 
LinkedList lnklist(v.begin(), v.end()); 

그래서 반복자 관용구를 사용하여 당신이 많은 힘과 유연성을 제공합니다. :-) 다른 사람처럼

1

설명한대로 Nawaz으로 반복기 솔루션을 사용하는 것이 좋습니다. 그러나 만약 당신이 배열 (정적 하나) 함께 가고 싶다면, 컴파일러는 자동으로 크기를 추론 할 수 있습니다.

template<size_t size> 
LinkedList::LinkedList(int (&array)[size]) 
{ 
    headPtr->setData(array[0]); //setData method stores the integer at position 0 inside headPtr 

    Node *currentPtr = headPtr; 

    for (int i = 0; i < size++i) //for loop to add the integers to the next node 
    { 
     currentPtr->setNext(new Node(array[i])); //creates a new node with the integer value of array position i 
    } 
} 

다음과 같이 호출 할 수 있습니다.

int arr[] = {1,2,3,4,5,6,7,8,9,10}; 

LinkedList lnklist(arr);