Question:
c++ help : please check code below : why cannot i run this? errors come up.?
Ashley Durban SA
2010-08-31 11:17:10 UTC
The sequential search algorithm does not assume that the list is in order.

Therefore, it usually works the same for both sorted and unsorted lists.

However, if the elements of
the list are sorted, then you can somewhat improve the performance of the sequential search
algorithm.

For example, if the search item is not in the list, you can stop the search as soon as you
find an element in the list that is larger than the search item.

Write the function seqOrdSearch to
implement a version of the sequential search algorithm for sorted lists.

Write a test program as well.

#include
#include
template
Iter seqOrdSearch(Iter beg, Iter end, const T& n)
{
for (; beg != end; ++beg)
{
if (*beg == n) break;
if (*beg > n) return end;
}
return beg;
}
int main()
{
std::list testlist = {1,5,7,8,8,9,100,120};
auto i1 = seqOrdSearch(testlist.begin(), testlist.end(), 8);
std::cout << "The number 8 was " << (i1==testlist.end()?"not ":"") << "found\n";
auto i2 = seqOrdSearch(testlist.begin(), testlist.end(), 11);
std::cout << "The number 11 was " << (i2==testlist.end()?"not ":"") << "found\n";
}
Three answers:
?
2010-08-31 14:57:45 UTC
You should say what errors come up, exactly. The error messages usually say what is wrong. On my compiler (GNU g++ 4.4.4) this compiles and runs with no errors.



If your compiler does not support initializer lists yet (they are a fairly new feature of C++), replace the line

     std::list testlist = {1,5,7,8,8,9,100,120};

with the lines

     int a[] = {1,5,7,8,8,9,100,120};

     std::list testlist(a, a+8);



after that, this program compiles and runs with MSVC 2010 Express Edition with no errors as well.



If your compiler is older than that, replace the word "auto" both times with the words "std::list::iterator", then it will be acceptable by any compiler written since 1998.
2016-12-12 15:15:22 UTC
I even have domicile windows xp, and that i'm getting the comparable concern on account that the day purely before this's afternoon. and that i've got regarded by way of multiple boards and anybody reported it truly is touching directly to the firewall or your laptop settings (this is the 1st decision). the 2d decision is that perchance some server in microsoft isn't working, and regrettably all our bills have been frozen.
peteams
2010-08-31 14:21:05 UTC
std::list testlist = {1,5,7,8,8,9,100,120};



You can't do that. If testlist were an array, a construct known to the compiler, you could write that.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...