作者的编码代码,从第一条记录到最后一条记录 [英] Code to Search book by its author from 1st record to last

查看:92
本文介绍了作者的编码代码,从第一条记录到最后一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!我卡在这里.我在Visual C ++中使用此代码按作者搜索一本书.我使用了冒泡排序然后进行二进制搜索的方法.

好吧,现在这就是我所拥有的.我现在想要做的是按作者搜索特定的书,而不使用冒泡排序或二进制搜索方法,而是一次搜索所有记录,从头到尾查找其作者.我认为改进的方法将使编码比现在短很多

Hey everyone! i stuck here with a thing. I use this code in visual c++ to search a book by its author. I have used the approach of bubble sorting then binary searching.

Alright, now this is what i have. what i want to do now is to search a particular BOOK by its author without using the bubble sorting or binary searching method and instead search all the records one at a time, from start till the end for its author. I think the improved approach will make the coding a lot shorter than it is now

//***************************************************************
//                   HEADER FILE USED IN PROJECT
//****************************************************************

#include<fstream> 
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<string.h>
#include<iomanip>
#include<iostream>


using namespace std;

class BOOK
{
public:
	char ID[6];
	char Content[50];
	char AUTHOR[20];
	char Book[20];
}  

void Copy(BOOK hd){ //  this function copies whole record
		strcpy(ID,(hd.ID)); //copy BOOK ki id
		strcpy(AUTHOR,(hd.AUTHOR)); // copy BOOK ka AUTHOR
		strcpy(Book,(hd.Book));
		strcpy(Content,(hd.Content));
}




	void SwapBOOK(BOOK &bk1, BOOK &bk2){ //swaps position of BOOK1 with BOOK2

	BOOK Temp;            

	Temp.Copy(bk1);  //BOOK1 ko temp main copy kiya
	bk1.Copy(bk2);   //BOOK2 ko BOOK1 main copy kiya (now BOOK2 has moved to the place of BOOK1)
	bk2.Copy(Temp);  //BOOK1 ko finalyy BOOK2 ki jaga per copy ker diya
}


//***************************************************************
//    	global declaration for stream object, object
//****************************************************************
fstream fp; // fstream provides an interface to read and write data from files as input/output streams.
ofstream ofp; // ofstream provides an interface to write data to files as output streams
//***************************************************************
//    	SORT AND SEARCH BY AUTHOR (START)
//****************************************************************



void SortByAUTHOR() // bubble sort
{
	for(int i=0; i< countBOOK-1; i++){
		for(int j=0; j <countBOOK-1; j++){
			if(strcmp(hd[j].AUTHOR,hd[j+1].AUTHOR)>0) 
				SwapBOOK(hd[j],hd[j+1]); // if above condition is satisfied, then call 'swapBOOK' function which is defined by us
		}
	}


}

//////////////////////////////////////////////////////////////////
void SearchBetweenIndex(int IndexA, int IndexB, char* AUTHOR)
{
	if(IndexA > IndexB){
		int temp;
		temp = IndexA;
		IndexA = IndexB;
		IndexB= temp;
	}

	for(int i = IndexA; i <= IndexB;i++){
		if(strcmp(hd[i].AUTHOR,AUTHOR)==0)
			hd[i].report();
	}

	getch();
}

/////////////////////////////////////////////////////////////////////

void ListByAUTHOR(char* AUTHOR){ //search by AUTHOR 	
	int PreviousIndex = 0; // first 

	int StartIndex =0 , EndIndex = countBOOK-1;
	
	int i=2;
	while(1==1){
		int CurrentIndex=(EndIndex+StartIndex)/2; //start searching from the mid position
		if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) > 0){ 
			PreviousIndex = EndIndex;
			EndIndex = CurrentIndex;
		}else if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) < 0){
			PreviousIndex = StartIndex;
			StartIndex = CurrentIndex;
		}else
			{
				SearchBetweenIndex(StartIndex, EndIndex, AUTHOR);
				break;
			}

		if(CurrentIndex == PreviousIndex)
			break;
	
		

	}

}


/////////////////////////////////////////////////////////////////////

void SortAndSearchByAUTHOR(){ // INPUT AUTHOR SEARCH CRITERIA
	system("cls");
	char str[50];
	cout << "Enter the Search Criteria for AUTHOR ";
	gets(str);
	SortByAUTHOR(); // CALL THIS FUNCTION
	ListByAUTHOR(str); // CALLL THIS FUNCTION

}

//***************************************************************
//    	SORT AND SEARCH BY AUTHOR ENDS
//****************************************************************

}

推荐答案

....而是一次搜索所有记录,从头到尾查找其作者.这种方法将使编码比现在短很多……"

?

如果您不想排序和搜索,则只需在所有书籍上循环(forwhile),然后列出符合搜索条件的书籍即可.

另外,如果您确实在使用C ++,我建议您使用诸如std :: vector,std :: string和所有其他STL算法之类的C ++构造,这将使您的生活更轻松.

祝你好运.
".... instead search all the records one at a time, from start till the end for its author. I think the improved approach will make the coding a lot shorter than it is now..."

?

If you do not want to sort and search, you can simply loop (for, while) over all your books and just list the books that fit the search criteria.

Also, if you really are using C++, I suggest that you use C++ constructs like std::vector, std::string and all other STL algorithms ... it will make your life easier.

Good luck.


你好smrizvi1,
我建议您使用STL,因为数组不是很...
STL更可靠,更易读.
它将改善您的方法

这是一个示例:

例如,说明通用二进制搜索算法的示例:
Hi smrizvi1,
I recommend that you use the STL, because array it''s not very...
STL is much more reliable,readable.
It will improve your approach

Here''s an example:

For example the illustrating the generic binary search algorithms:
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
  vector<int> v(5);
  bool found;

  for (int i = 0; i < 5; ++i)
     v[i] = i;

  found = binary_search(v.begin(), v.end(), 3);
  cout << found << " ";

  // Try searching for a value that''s not present:
  found = binary_search (v.begin(), v.end(), 9);
  cout << found;

  return 0;
}



关于使用STL进行排序,您可以在这里阅读:
http://create.stephan-brumme.com/stl-sort/ [ http://www.cplusplus.com/reference/algorithm/sort/ [ http://login2win.blogspot.com/2011/06/bubble-sort-in- c.html

或在这里:
http://www.java2s.com/Tutorial/Cpp/0100__Development/ABubblesort.htm [ ^ ]

就这样.

P/S如果它对您有所帮助,请不要忘记投票! :)



About sorting with STL you can read here:
http://create.stephan-brumme.com/stl-sort/[^]

http://www.cplusplus.com/reference/algorithm/sort/[^]

About simple buble sort you can read here:
http://login2win.blogspot.com/2011/06/bubble-sort-in-c.html

or here:
http://www.java2s.com/Tutorial/Cpp/0100__Development/ABubblesort.htm[^]

That''s all.

P/S Do not forget to vote if it helped you! :)


在我之后重复...

当我用C ++进行搜索时,如果我不使用std::sortstd::find,我会去打自己的脑袋,或者,最好是因为我不喜欢痛苦,我将重写我的课程,这样可以放在一个集合中,并进行分类和搜索."

话虽如此,如何编写一个使该类的对象能够将对象粘贴到集合中以便可以使用std::sortstd::find的类?对于简单对象,答案是非常简单的:您只需要一个小于运算符(对于std::sort)和一个相等运算符(对于std::find).

如果使用这两个,则不需要任何显式循环和std::sort的实现(通常先使用O(nlogn)排序,然后在分区足够小时切换到O(n平方)算法)和std::find(通常使用二进制搜索,O(logn))还不错.为它们计时并查看您的数据集.

只是为了向您展示这是多么容易,请看下面的代码.它还不完整,但是显示了如果您知道如何实现类,那么排序和搜索可以多么简单:
Repeat after me...

"When I do a search in C++ and I don''t use std::sort and std::find I shall go and punch myself in the head OR, preferably as I don''t like pain, I shall rewrite my class so it can be put in a collection and sorted and searched."

Having said that, how can you write a class that enables objects of the class to stick an object in a collection so you can use std::sort and std::find? For simple objects the answer is remarkably, er, simple: You just need a less than operator (for std::sort) and an equality operator (for std::find).

If you use these two you don''t need any explicit loops AND the implementations of std::sort (usually uses an O(nlogn) sort at first and then switches to an O(n squared) algorithm when the partitions get small enough) and std::find (usually uses a binary search, O(logn) ) aren''t too bad. Time them and see with your data set.

Just to show you how easy this is have a look at the following code. It''s not complete but it shows how simple sorting and searching can be if you know how to implement your classes:
#include <string>
#include <ostream>
#include <vector>
#include <algorithm>
    
class book
{
    public:
        book( const std::string &title, const std::string &author )
            : title_( title ), author_( author )
        {
        }

        friend bool operator<( const book &, const book & );
        friend bool operator==( const book &, const book & );
        friend std::ostream &operator<<( std::ostream &, const book & );

    private:
        std::string title_;
        std::string author_;
};

bool operator<( const book &a, const book &b )
{
    return a.author_ < b.author_;
}

bool operator==( const book &a, const book &b )
{
    return a.author_ == b.author_;
}

std::ostream &operator<<( std::ostream &output_to, const book &to_output )
{
    return output_to << "Title:  "   << to_output.title_
                     << "\nAuthor: " << to_output.author_;
}

const book books_you_should_read[] =
{
    book( "The C++ Programming Language", "Stroustrup, Bjarne" ),
    book( "Standard C++ IOStreams and Locales", "Langer, Angela" ),
    book( "Exceptional C++", "Sutter, Herb" ),
    book( "Effective C++", "Myers, Scott" ),
    book( "Accelerated C++", "Koenig, Andrew" )
};

void book_test( std::ostream &output )
{
    std::vector<book> library( std::begin( books_you_should_read ),
                                     std::end( books_you_should_read ) );

    std::sort( std::begin( library ), std::end( library ) );

    auto found = std::find( std::begin( library ),
                            std::end( library ),
                            book( "Anything", "Stroustrup, Bjarne" ) );

    if( found != std::end( library ) )
    {
        output << "Found:\n" << *found << std::endl;
    }
    else
    {
        output << "Couldn't find a book by God" << std::endl;
    }
}


该代码不是C ++编码的典范,因为:

-一切都内联
-书不是一门有用的课程-要由您决定使其有用
-我没有使用过任何PIMP或其他编译防火墙
-它没有显示编写类似于内置类型的类所需的所有成员

很好,是因为:

-真的很简单,所有的复杂性都由类管理
-没有明确的循环
-很少的条件代码

哦,如果这是功课:

-请在您的C ++实践中以此为灵感,它虽然不完美,但要点也不算太差
-如果您复制并上交,可能会在自己的内中燃烧
-如果您将其复制并交上好成绩,然后要求您退还课程费用,则您的讲师会因为没有教给您正确的事情或错误的顺序而感到沮丧.无论哪种方式,他都是对你不利的布偶
-请参阅对您有帮助的书籍清单.从"Accelerated C ++"开始,然后从那里开始

编辑是因为我讨厌这个编辑器,它试图变得太聪明了,我也是,所以我修复了一个错误

PS:从解决方案4 ...

您开始做数据库做的事情.您可以从他们的书中摘取叶子,并为可以排序和查找的所有可能值构建索引.因此,您无需对书籍vector进行排序和查找,而是对book代理对象的集合进行处理,其中一个或多个代理对象将在书籍的载体中代表作者.

除了对数组进行排序和搜索外,您还不如花一整头猪,并使用一对std::multimaps:


This code isn''t a paragon of C++ coding because:

- Everything''s inline
- book isn''t a useful class - up to you to make it useful
- I haven''t used any PIMPs or other compilation firewalls
- It doesn''t show all the members you need to write a class that works like a built in type

It''s good because:

- It is really simple, all the complexity is managed by the class
- No explicit loops
- Very little conditional code

Oh, and if this is homework:

- Please use this as inspiration in your C++ practice, it ain''t perfect but the salient points aren''t too bad
- If you copy this and hand it in may you burn in your own hell of personal guilt
- If you copy this and hand it in AND get a good mark then demand your course fee back, your lecturer is crap either by not teaching you the right things or in the wrong order. Either way he''s a muppet that''s doing you no favours
- Please see the list of books it''d be good for you to read. Start with "Accelerated C++" and go from there

Edited because I hate this editor, it tries to be too effing clever and so was I, so I fixed a bug

PS: From solution 4...

You''re starting to do the sort of thing that databases do. You could take a leaf out of their book and construct indexes of all the possible values you could sort and find on. So instead of sorting and finding on the vector of books you''d do it on a collection of book proxy objects, one or more of which would represent the author in the vector of books.

Instead of sorting and searching an array you might as well go the whole hog and use a pair of std::multimaps:

std::multimap<const std::string &, const book &> book_title_name_index;
std::multimap<const std::string &, const book &> author_name_index;

然后将标题中的每个单词(无标点符号)砍掉,并在标题中为每个单词粘贴每本书的作者和地图中的书籍.因此JRRTolkien撰写的两座塔楼"在book_title_name_index中将有3个条目,其中一个与"The"(您可能希望清除经常出现的常用词)相对应,两个"和塔楼"以及一个"Tolkien"在author_name_index 中,因为您不希望姓名首字母大写地修饰作品.

然后,您将可以使用multimap 上的find 功能来查找带有单词match的书,例如:

Then hack out each word (sans punctuation) in the title and author of each book sticking the word and the book in the map for each word in the title. So "The Two Towers" by J.R.R.Tolkien would have three entries in the book_title_name_index, one against "The" (you might like to weed out common words that appear frequently), "Two" and "Towers" and one "Tolkien" in the author_name_index as you don''t want initials munging up the works.

Then you''ll be able to use either the find function on multimap to find a book with the word match, e.g:

auto book_location = book_title_index.find( "Towers" );
if( book_location != end( book_title_index ) )
{
    std::cout << "found:" << *book_location;
}


或使用equal_range函数获取符合您设置的条件的任何书籍.

所以方法是...

-将您要使用的对象保存在易于访问的地方
-通过引用一次或多次将对象粘贴到一个或多个multimaps 中,这些multimaps 由要使用的搜索参数键入.
-使用find equal_range 来获取您感兴趣的对象.


or use the equal_range function to get any books that match the criteria you set.

So the method is...

- Save the objects you want to work with somewhere easily accessible
- Stick the objects by reference one or more times into one or more multimaps that are keyed by the search parameters you want to use.
- Use find or equal_range to get the objects you''re interested in.


这篇关于作者的编码代码,从第一条记录到最后一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆