コード例 #1
0
void StatusStructure::move(size_t from, size_t to) {
    if (to >= m_tree.size()) {
        return;
    }

    // Movement must be recursive and breath-first instead of depth-first (otherwise we would overwrite elements before they are moved)
    std::queue<std::pair<size_t, size_t>> moveQueue;
    moveQueue.push(std::make_pair(from, to));

    while (!moveQueue.empty()) {
        from = moveQueue.front().first;
        to = moveQueue.front().second;
        moveQueue.pop();

        auto toMoveFrag = getAt(from);
        insertAt(to, toMoveFrag);

        if (toMoveFrag != nullptr) {
            // move the children of the moved element
            insertAt(from, nullptr);                                                           // clear the element
            moveQueue.push(std::make_pair(getLeftChildIndex(from), getLeftChildIndex(to)));    // move left children
            moveQueue.push(std::make_pair(getRightChildIndex(from), getRightChildIndex(to)));  // move right children
        }
    }
}
コード例 #2
0
int OptionListWidget::insertAt(QPoint position, OptionWidget *optionWidget) {
    QPoint centeredPosition(x() + 0.5 * width(), position.y());

    if(position.y() <= 0) { //position is above widget
        insertAt(0, optionWidget);
        return 0;

    } else if(y() + height() <= position.y()) { //position is below widget => insert at the end
        add(optionWidget);
        return options->size();

    } else { //y position is in widget
        int insertBelow = 0;
        for (int i = 0; i < options->size() && i == insertBelow; ++i) {
            if(options->at(i)->frameGeometry().top() >= position.y() ||
                options->at(i)->frameGeometry().contains(centeredPosition)) {
                insertAt(i, optionWidget);
            } else {
                insertBelow += 1;
            }
        }
        if(insertBelow == options->size()) {//widget was still not inserted
            add(optionWidget);
        }
        return insertBelow;
    }
};
コード例 #3
0
ファイル: linkedList.c プロジェクト: MGreathouse/cs340
int main(void) {
    Node *head = NULL, *tail = NULL;
    int i;

    for(i = 0; i < 10; i++) {
        append(createNode(10-i), &head, &tail);
    }

    insertAt(11, &head, &tail, 5);
    insertAt(12, &head, &tail, 0);
    insertAt(13, &head, &tail, 15);
    insertAt(15, &head, &tail, 8);
    insertAt(16, &head, &tail, 7);
    sortedInsert(14, &head, &tail);

    printNodes(head);
    printf("\nThere are %d Nodes in this linked list.\n\n\n", count(head));

    sort(&head, &tail);

    printNodes(head);
    printf("\nThere are %d Nodes in this linked list.\n\n", count(head));

    return 0;
}
コード例 #4
0
ファイル: task_3(dek).cpp プロジェクト: GNazar/tasks_3
int _tmain(int argc, _TCHAR* argv[])
{
	for(int i=(int)0;i<4;i++){
		pushBack(i*i);
	}
	puts("print()");
	print();
	getchar();

	puts("insertAt(1,-100)");	//insert element;
	insertAt((int)1,(int)-100);
	print();
	getchar();

	puts("popFront()");		//delete first element; 
	popFront();
	print();
	getchar();

	puts("popBack()");		//delete last element;
	popBack();
	print();
	getchar();

	puts("pushFront(-1)");	//insert element at first position;
	pushFront((int)-1);
	print();
	getchar();

	printf("at(3)=%d\n",at((int)3));//get 3rd element;
	getchar();

	puts("insertAt(size,-3)");	//delete element;
	insertAt(size,(int)-3);
	print();
	getchar();

	puts("deleteAt(1)");	//delete element;
	deleteAt((int)1);
	print();
	getchar();

	puts("Free list");		//delete all elements;
	delDEQ();
	print();
	getchar();
	return 0;
}
コード例 #5
0
void StatusStructure::remove(const LineSegmentPtr& fragment) {
    bool valid;
    size_t index = indexOf(fragment, valid);

    if (!valid) {
        return;
    }

    m_index_map.erase(fragment);

    if (leftChild(index) == nullptr) {
        move(getRightChildIndex(index), index);
        return;
    } else if (rightChild(index) == nullptr) {
        move(getLeftChildIndex(index), index);
        return;
    }

    // get direct left neighbour of index (most right child in left subtree)
    size_t directLeftNeighbourIndex = getLeftChildIndex(index);
    while (rightChild(directLeftNeighbourIndex) != nullptr) {
        directLeftNeighbourIndex = getRightChildIndex(directLeftNeighbourIndex);
    }

    insertAt(index, getAt(directLeftNeighbourIndex));
    move(getLeftChildIndex(directLeftNeighbourIndex), directLeftNeighbourIndex);
}
コード例 #6
0
ファイル: PyView.cpp プロジェクト: SASfit/SASfit
int PyView::setSlice(int s, int e, const PWOSequence& lst) {
  int sz = GetSize();
  if (s < 0)
    s += sz;
  if (e < 0)
    e += sz;
  if (e > sz)
    e = sz;
  int i = 0;
  for (; i < lst.len() && s < e; i++, s++)
    setItem(s, lst[i]);
  for (; i < lst.len(); i++, s++)
  {
    if (_base)
      Fail(PyExc_RuntimeError, "Can't insert in this view");
    insertAt(s, lst[i]);
  }
  if (s < e)
    if (_base)
      while (s < e)
      {
        int ndx = _base->GetIndexOf(GetAt(s));
        _base->RemoveAt(ndx, 1);
        --e;
      }
    else
      RemoveAt(s, e - s);
  return 0;
}
コード例 #7
0
ファイル: text.cpp プロジェクト: hamumu/OOP344-20123
 void Text::insertAndBreakAt(unsigned int index, unsigned int charIndex){
   Text& T = *this;
   insertAt(index);
   if(index && T[index-1].strlen() > charIndex){
     T[index] = &T[index-1][charIndex];
     T[index-1][charIndex] = 0;
   }
 }
コード例 #8
0
ファイル: ScriptEditor.cpp プロジェクト: spaceyatom/mantid
/**
 * Set the text on the given line, something I feel is missing from the QScintilla API. Note
 * that like QScintilla line numbers start from 0
 * @param lineno :: A zero-based index representing the linenumber, 
 * @param txt :: The text to insert at the given line
 * @param index :: The position of text in a line number,default value is zero
 */
void ScriptEditor::setText(int lineno, const QString& txt,int index)
{
  int line_length = txt.length();
  // Index is max of the length of current/new text
  setSelection(lineno, index, lineno, qMax(line_length, this->text(lineno).length()));
  removeSelectedText();
  insertAt(txt, lineno, index);
  setCursorPosition(lineno, line_length);
}
コード例 #9
0
ssize_t VectorImpl::resize(size_t size) {
    ssize_t result = NO_ERROR;
    if (size > mCount) {
        result = insertAt(mCount, size - mCount);
    } else if (size < mCount) {
        result = removeItemsAt(size, mCount - size);
    }
    return result < 0 ? result : size;
}
コード例 #10
0
void StatusStructure::swapNeighbours(LineSegmentPtr a, LineSegmentPtr b) {
    assert(leftNeighbourOf(a) == b || rightNeighbourOf(a) == b);

    bool valid;
    size_t a_index = indexOf(a, valid);

    if (!valid) {
        throw std::runtime_error("StatusStructure::swapNeighbours: Invalid argument fragment a does not exist.");
    }

    size_t b_index = indexOf(b, valid);

    if (!valid) {
        throw std::runtime_error("StatusStructure::swapNeighbours: Invalid argument fragment b does not exist.");
    }

    insertAt(a_index, b);
    insertAt(b_index, a);
}
コード例 #11
0
void LinkedListPriorityQueue::enqueue(string value) {
    for (List* item = head; item != NULL; item = item->next) {
        if (item->next == NULL || item->next->value > value) {
            insertAt(item, value);
            break;
        }
    }    
  
    qSize++;    
}
コード例 #12
0
ファイル: avltree.cpp プロジェクト: triffon/sdp-2015-16
	// -1 --- неуспешно включване, елементът вече го има
	// 0  --- успешно включване, но няма промяна във височината
	// 1  --- успешно включване и има увеличение на височината с 1
	int insertAt(P p, T const& x) {
		if (!p) {
			// дъно
			BinaryTree<AVL>::assignFrom(p, AVL(x));
			return 1;
		}
		// p --- валидна позиция
		if ((*p).data() == x)
			// Грешка! x вече го има
			return -1;
		// p && *p != x
		int result;
		if (x < (*p).data()) {
			// вмъкваме наляво
			result = insertAt(-p, x);
			if (result == 1) {
				(*p).balance()--;
				if ((*p).balance() == -2) {
					if ((*-p).balance() == 1)
						rotateLeft(-p);
					rotateRight(p);
					result = 0;
				}
			}
		} else {
			// вмъкваме надясно
			result = insertAt(+p, x);
			if (result == 1) {
				(*p).balance()++;
				if ((*p).balance() == 2) {
					if ((*+p).balance() == -1)
						rotateRight(+p);
					rotateLeft(p);
					result = 0;
				}
			}
		}
		// ако сме вмъкнали успешно и балансът се е получил 0
		// значи нямаме промяна във височината
		if (result >= 0 && (*p).balance() == 0)
			result = 0;
		return result;
	}
コード例 #13
0
ファイル: q3glist.cpp プロジェクト: stephaneAG/PengPod700
void Q3GList::inSort( Q3PtrCollection::Item d )
{
    int index = 0;
    register Q3LNode *n = firstNode;
    while ( n && compareItems(n->data,d) < 0 ){ // find position in list
	n = n->next;
	index++;
    }
    insertAt( index, d );
}
コード例 #14
0
ファイル: linkedList.c プロジェクト: GArlington/uml2code
int main() {
	printf("*** String-linked-list by RoD ***\n\n");
	printf("Demo of a string's list:\n");
	struct LinkedList *demo = NULL;
	demo = insert(demo, "Linea uno");
	demo = insert(demo, "Linea dos");
	demo = insert(demo, "Linea tres");
	printf("La segunda linea dice: '%s'\n", elementAt(1,demo));
	printlist(demo);
	
	
	// File name length of 500
	char name_of_file[500];
	printf("\nNow you can write the name a the file to open:\n");
	scanf("%s", name_of_file);
	FILE *f;
	f = fopen(name_of_file, "r");
	if(f == NULL) {
		printf("Can't open the file ('%s')\nExiting now...\n", name_of_file);
		return 0;
	}
	printf("Opening file '%s' [ OK ]\n", name_of_file);
	char buffer[151];
	struct LinkedList *start = NULL;
	while(!feof(f)){
		if(fgets(buffer,150,f)){
			ejlines(buffer);
			start = insert(start, buffer);
		}
	}
	printf("End of file\n");
	fclose(f);
	
	start = insertAt(193,"Rodrigo es el mejor", start);
	start = insertAt(0, "Me falto esto al iniciar", start);
	start = insertAt(1, "Y esto después de lo que me faltó", start);
	
	printlist(start);
	
	
	return 0;
}
コード例 #15
0
bool str::replaceLast(const char* pFind, const char* pWith)
{
    const int findIndex = lastIndexOf(pFind);
    if(findIndex != mInvalidIndex)
    {
        eraseAfter(findIndex, strlen(pFind));
        insertAt(findIndex, pWith);
        return true;
    }
    return false;
}
コード例 #16
0
ファイル: LinkedList.cpp プロジェクト: UmanShahzad/StringMap
LinkedList<Item>::LinkedList(const LinkedList<Item>& _linkedList)
  : head(NULL) {
  // Create a rhs traverser.
  Node<Item>* traverser = _linkedList.head;

  // Loop through the items, adding them with insertAt(loc: int, item: Item).
  for (int i = 0; i < _linkedList.size; i++) {
    insertAt(i, traverser->getKey(), traverser->getValue());
    traverser = traverser->getNext();
  }
}
コード例 #17
0
void DLL_EXPORT DynamicArray<T,chrunkSize>::insertAt(size_t index, T &item)
{
    bool mustMove = index < size;

    this->setToSize(index + 1);

    T cvalue = this->get(index);

    this->set(index, item);

    if (mustMove)                   // this way the tail-recursion can be optimized by compiler
        insertAt(index+1, cvalue);
}
コード例 #18
0
void OptionListWidget::dropEvent(QDropEvent *event) {
    bool noError = true;
    qlonglong data = event->mimeData()->data(tr("OptionWidget")).toULongLong(&noError, 16);
    OptionWidget* widget = reinterpret_cast<OptionWidget*>(data);
    if(options->contains(widget)) {
        int oldIndex = options->indexOf(widget);
        int newIndex = insertAt(event->pos(), widget);
        if (oldIndex < newIndex)
            options->removeAt(oldIndex);
        else
            options->removeAt(oldIndex + 1);
    }
};
コード例 #19
0
int main()
{
    List ls;
    ls.count = 0;
    ls.first = NULL;

    int number = 0;
    scanf("%d", &number);
    int i = 0, temp;
    while (i < number) {
        scanf("%d", &temp);
        insertAt(&ls, i, temp);
        i++;
    }
    print(&ls, stdout);
    printf("\n");

    i = 1;
    while (i < 6) {
        insertFront(&ls, i);
        i++;
    }
    print(&ls, stdout);
    printf("\n");

    i = 1;
    int nums = getSize(&ls);
    while (i < nums) {
        deleteAt(&ls, i);
        i++;
        nums--;
    }
    print(&ls, stdout);
    printf("\n");

    i = 0;
    nums = getSize(&ls);
    while (i < getSize(&ls)) {
        if (getAt(&ls, i) < 3) {
            deleteAt(&ls, i);
            i--;
        } else {
            setAt(&ls, i, getAt(&ls, i) * 10);           
        }
        i++;
    }
    print(&ls, stdout);


    return 0;
}
コード例 #20
0
int str::replaceAll(const char* pFind, const char* pWith)
{
    int count = 0;
    int findIndex = mInvalidIndex;

    while(mInvalidIndex != (findIndex = firstIndexOf(pFind)))
    {
        eraseAfter(findIndex, strlen(pFind));
        insertAt(findIndex, pWith);
        ++count;
    }

    return count;
}
コード例 #21
0
ファイル: IdHash.cpp プロジェクト: anliec/TP-Algo
unsigned IdHash::addId(const unsigned &id)
/* Algorithm : checks if the id already exists.
 */
{
    unsigned idInTab, pos=hashFunction(id);
    if(alreadyAdded(id,pos,idInTab))
    {
        return idInTab;
    }
    else
    {
        return insertAt(pos,id);
    }
}
コード例 #22
0
ファイル: TestLst.cpp プロジェクト: AndersEdin/Okasaki
List<char> test2()
{
	auto lst3 = test1(); // {b, a}
	// b: ref 1
	// a: ref 1
    std::cout << lst3 << std::endl;
	auto lst4 = lst3.insertAt(1, 'x'); // {b, x, a}
	// x: ref 1
	// b: ref 2
	// a: ref 1
    std::cout << lst4 << std::endl;
	auto lst5 = concat(lst3, lst4);
    std::cout << lst5 << std::endl;
	return lst5;
}
コード例 #23
0
ファイル: TestLst.cpp プロジェクト: ETK/Okasaki
List<char> test2()
{
	auto lst3 = test1(); // {b, a}
	// b: ref 1
	// a: ref 1
	print(lst3);
	auto lst4 = lst3.insertAt(1, 'x'); // {b, x, a}
	// x: ref 1
	// b: ref 2
	// a: ref 1
	print (lst4);
	auto lst5 = concat(lst3, lst4);
	print(lst5);
	return lst5;
}
コード例 #24
0
ファイル: qgscodeeditor.cpp プロジェクト: Ariki/QGIS
void QgsCodeEditor::insertText( const QString theText )
{
  // Insert the text or replace selected text
  if ( hasSelectedText() )
  {
    replaceSelectedText( theText );
  }
  else
  {
    int line, index;
    getCursorPosition( &line, &index );
    insertAt( theText, line, index );
    setCursorPosition( line, index + theText.length() );
  }
}
コード例 #25
0
ファイル: linkedList.c プロジェクト: MGreathouse/cs340
// adds a new node at a location where it should go assuming the list is sorted
void sortedInsert(int value, Node **head, Node **tail) {
    Node *ptr = *head;
    int loc = 0;

    if (*head == NULL) {
        append(createNode(value), head, tail);
    } else {
        if (ptr -> data > value) {
            insertAt(value, head, tail, 0);
        } else {
            while (ptr -> next != NULL && (ptr -> next) -> data < value) {
                ptr = ptr -> next;
                loc++;
            }

            // check to see if we are simply at the end or if we are where we need to be
            if (ptr -> next == NULL) {
                append(createNode(value), head, tail);
            } else {
                insertAt(value, head, tail, ++loc);
            }
        }
    }
}
コード例 #26
0
int
PositionVector::insertAtClosest(const Position& p) {
    Position outIntersection = Position();
    SUMOReal minDist = std::numeric_limits<SUMOReal>::max();
    SUMOReal dist;
    int insertionIndex = 1;
    for (int i = 0; i < (int)size() - 1; i++) {
        dist = GeomHelper::closestDistancePointLine2D(p, (*this)[i], (*this)[i + 1], outIntersection);
        if (dist < minDist) {
            insertionIndex = i + 1;
            minDist = dist;
        }
    }
    insertAt(insertionIndex, p);
    return insertionIndex;
}
コード例 #27
0
ファイル: LinkedList.cpp プロジェクト: UmanShahzad/StringMap
LinkedList<Item>& LinkedList<Item>::operator=(const LinkedList<Item>& rhs) {
  // First disassemble the existing list.
  this->~LinkedList();

  // Create a rhs traverser.
  Node<Item>* traverser = rhs.head;

  // Now assign variables.
  head = NULL;

  for (int i = 0; i < rhs.size; i++) {
    insertAt(i, traverser->getKey(), traverser->getValue());
    traverser = traverser->getNext();
  }

  return *this;
}
コード例 #28
0
void KEdit::replace_slot()
{

    if(!replace_dialog)
        return;

    if(!can_replace)
    {
        KNotifyClient::beep();
        return;
    }

    int line, col, length;

    QString string = replace_dialog->getReplaceText();
    length = string.length();

    this->cut();

    getCursorPosition(&line, &col);

    insertAt(string, line, col);
    setModified(true);
    can_replace = false;

    if(replace_dialog->get_direction())
    {
        // Backward
        setCursorPosition(line, col + length);
        for(int k = 0; k < length; k++)
        {
            cursorLeft(true);
        }
    }
    else
    {
        // Forward
        setCursorPosition(line, col);
        for(int k = 0; k < length; k++)
        {
            cursorRight(true);
        }
    }
}
コード例 #29
0
void StatusStructure::insert(LineSegmentPtr fragment, const Point& scanLinePosition) {
    size_t currentIndex = 0;
    auto currentFrag = getAt(currentIndex);

    while (currentFrag != nullptr) {
        if (currentFrag == fragment) {
            return;
        }

        if (isALeftOfBOnScanLine(*fragment, *currentFrag, scanLinePosition)) {
            currentIndex = getLeftChildIndex(currentIndex);
        } else {
            currentIndex = getRightChildIndex(currentIndex);
        }

        currentFrag = getAt(currentIndex);
    }

    insertAt(currentIndex, fragment);
}
コード例 #30
0
ファイル: editor.cpp プロジェクト: JustDevZero/pdfedit5
void Editor::commentSelection()
{
    int paragraphStart;
    int paragraphEnd;
    int indexStart;
    int indexEnd;
    getSelection(&paragraphStart, &indexStart, &paragraphEnd, &indexEnd);

    if (paragraphStart < 0) {
        getCursorPosition(&paragraphStart, &indexStart);
        paragraphEnd = paragraphStart;
    }

    if (paragraphStart >= 0 && paragraphEnd >= 0) {
        for (int i=paragraphStart; i<=paragraphEnd; ++i)
            insertAt(QString::fromLatin1("//"), i, 0);

        repaintChanged();
        setModified(TRUE);
    }
}