Error scalar object a requires one element in initializer

Why does this code give this error scalar object 'suits' requires one element in initializer Code: const char *suits = {'h', 'd', 'c', 's'};
  1. 05-27-2015


    #1

    telmo_d is offline


    Registered User


    Join Date
    Apr 2015
    Posts
    180

    scalar object requires one element in initializer

    Why does this code give this error scalar object ‘suits’ requires one element in initializer

    Code:

    const char *suits = {'h', 'd', 'c', 's'};


  2. 05-27-2015


    #2

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,416

    The «why» is probably because you cannot initialise a pointer with an aggregate.

    If you’re willing to let there be a terminating null character, I suggest:

    Code:

    const char *suits = "hdcs";

    Otherwise, just make suits an array:

    Code:

    const char suits[] = {'h', 'd', 'c', 's'};

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  3. 05-27-2015


    #3

    telmo_d is offline


    Registered User


    Join Date
    Apr 2015
    Posts
    180

    Why does this work?

    Code:

    char* Numbers[] = {"-----", ".----", "..---", "...--", "....-", ".....", "-....","--...", "---..", "----."};


  4. 05-27-2015


    #4

    telmo_d is offline


    Registered User


    Join Date
    Apr 2015
    Posts
    180

    What the heck is wrong with this? too many initializers for ‘char []’

    Code:

    char suits[] = {"h", "d", "c", "s"};


  5. 05-27-2015


    #5

    Satya is offline


    Registered User


    Join Date
    Feb 2012
    Posts
    347

    it should be

    Code:

    char suits[] = {'h', 'd', 'c', 's'};


  6. 05-27-2015


    #6

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,416

    Quote Originally Posted by telmo_d

    Why does this work?

    Code:

    char* Numbers[] = {"-----", ".----", "..---", "...--", "....-", ".....", "-....","--...", "---..", "----."};

    You are initialising an array of pointers to char using an initialiser list of string literals. That is fine, since each string literal in the list can be used to initialise a pointer to char.

    Quote Originally Posted by telmo_d

    What the heck is wrong with this? too many initializers for ‘char []’

    Code:

    char suits[] = {"h", "d", "c", "s"};

    You are trying to initialise an array of char using an initialiser list of string literals. This is problematic: how can each string literal in the list be used to initialise a single char?

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


Привет,

У меня есть простой код, показанный ниже, сохраненный в файл (скажем, stock_portfolio.cxx).

Я пытаюсь скомпилировать это как:
g++ stock_portfolio.cxx

но я получаю следующую ошибку на этапе компиляции:

error: scalar object 'v' requires one element in initializer

У меня есть версия gcc:
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)

#include<iostream>
#include<vector>
int main() {
std::vector<int>v = {1,2,3,4,5,6};
//std::vector<string> four_star_stocks;
for(int i = 0; i < v.size(); ++i){
std::cout << "Stock S&P: " << v[i] << "n";
}
std::cout << "========================" << "n";
std::cout << "Totals   : " << v.size() << "n";
return 0;
}

3

Решение

инициализация списка была введена в C ++ только в C ++ 11. gcc версии 4.1 не поддерживает C ++ 11 (см. https://gcc.gnu.org/projects/cxx0x.html)

Для меня неясно, спрашиваете ли вы о предлагаемом решении / исправлении или о том, почему ваш код не будет компилироваться.

2

Другие решения

Инициализируйте ваш вектор в цикле, например так:

for(int i = 1; i <= 6; ++i)
v.push_back(i);

Как подсказывает cdhowie, ваша версия gcc не поддерживает список инициализаторов (вам нужна, по крайней мере, версия g ++ 4.4, источник). В случае, если вы получите более новый (добавив флаг -std=c++0x или же -std=gnu++0x), то вы можете увидеть следующее:

std::vector<int> v = {1,2,3,4,5,6};

или же

Если вы хотите сделать это со списком инициализаторов, то вы должны использовать std :: initializer_list следующим образом:

#include <iostream>
#include <vector>
#include <initializer_list>

template <class T>
struct S {
std::vector<T> v;
S(std::initializer_list<T> l) : v(l) {
std::cout << "constructed with a " << l.size() << "-element listn";
}
void append(std::initializer_list<T> l) {
v.insert(v.end(), l.begin(), l.end());
}
std::pair<const T*, std::size_t> c_arr() const {
return {&v[0], v.size()};  // list-initialization in return statement
// this is NOT a use of std::initializer_list
}
};

template <typename T>
void templated_fn(T) {}

int main()
{
S<int> s = {1, 2, 3, 4, 5}; // direct list-initialization
s.append({6, 7, 8});      // list-initialization in function call

std::cout << "The vector size is now " << s.c_arr().second << " ints:n";

for (auto n : s.v) std::cout << ' ' << n;

std::cout << 'n';

std::cout << "range-for over brace-init-list: n";

for (int x : {-1, -2, -3}) // the rule for auto makes this ranged for work
std::cout << x << ' ';
std::cout << 'n';

auto al = {10, 11, 12};   // special rule for auto

std::cout << "The list bound to auto has size() = " << al.size() << 'n';

//    templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression,
// it has no type, and so T cannot be deduced
templated_fn<std::initializer_list<int>>({1, 2, 3}); // OK
templated_fn<std::vector<int>>({1, 2, 3});           // also OK
}

Источник

0

Number Sort

Pages: 12

I’m not really sure how to fix this, and I’m also not sure how to add a section that counts how many times the numbers are compared in each function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;
int FindIndexOfSmallest(int array[], int low, int high);
void SelectionSort(int array[], int size);
int A = {50, 30, 66, 10, 168, 45, 99, 20};
int main()
{
 FindIndexOfSmallest(array[A], low, high);
 SelectionSort(array[A], 8);
}
int FindIndexOfSmallest(int array[], int low, int high)
{
	int i, pos = low;
	for (i=low; i<=high; i++)
        {
	      if (array[i] < array[pos]) pos = i;
	    }
	return pos;
}
void SelectionSort(int array[], int size)
{
    int startScan, minIndex, minValue;

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++)
        {
            if (array[index] < minValue)
            {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

Hello Spiderman30,

You should try compiling you program to see what errors you get which help a great deal in figuring out what is wrong with your program.

There are several things missing from your program that need fixed before you can proceed.

Andy


||=== Build: Debug in Number Sort (compiler: GNU GCC Compiler) ===|
C:UsersmycomOneDriveDocumentsNumber Sortmain.cpp|6|error: scalar object 'A' requires one element in initializer|
C:UsersmycomOneDriveDocumentsNumber Sortmain.cpp||In function 'int main()':|
C:UsersmycomOneDriveDocumentsNumber Sortmain.cpp|9|error: 'array' was not declared in this scope|
C:UsersmycomOneDriveDocumentsNumber Sortmain.cpp|9|error: 'low' was not declared in this scope|
C:UsersmycomOneDriveDocumentsNumber Sortmain.cpp|9|error: 'high' was not declared in this scope|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 3 second(s)) ===|

Hello Spiderman30,

That is nice, but do you know what is wrong and how to fix it?

Andy

Edit:

Last edited on

Since the syntax here is super wrong, let me start by saying

1
2
 int A = {50, 30, 66, 10, 168, 45, 99, 20};
 SelectionSort(array[A], 8);

is not how it’s done. You forgot the necessary [] to denote that A is an array, and you’re doing some weird stuff when you try to pass it into the function.
Just do

1
2
 int A[] = {50, 30, 66, 10, 168, 45, 99, 20};
 SelectonSort(A, 8);

See http://www.cplusplus.com/doc/tutorial/arrays/ «Arrays as parameters» section.

_________________________________________

1
2
error: 'low' was not declared in this scope
error: 'high' was not declared in this scope

This error is pretty clear. You never declared variables named low and high anywhere.
What values are being passed to FindIndexOfSmallest()?

Last edited on

I wanted to pass the values of the array through both functions. I see what you are saying, and I tried that but I still get some strange output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

int main()
{
int low;
int high;
int FindIndexOfSmallest(int array[], int low, int high);
void SelectionSort(int array[], int size);
int [A] = {50, 30, 66, 10, 168, 45, 99, 20};
 FindIndexOfSmallest([A], low, high);
 SelectionSort(A, 8);
}
int FindIndexOfSmallest(int array[], int low, int high)
{
	int i, pos = low;
	for (i=low; i<=high; i++)
        {
	      if (array[i] < array[pos]) pos = i;
	    }
	return pos;
}
void SelectionSort(int array[], int size)
{
    int startScan, minIndex, minValue;

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++)
        {
            if (array[index] < minValue)
            {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

your code:
int [A] = {50, 30, 66, 10, 168, 45, 99, 20};

my code:
int A[] = {50, 30, 66, 10, 168, 45, 99, 20};

See the difference?

You’re calling SelectionSort correctly now. But you still have wrong syntax when calling FindIndexOfSmallest. Both want arrays. Pass in the array the same way you passed in the array to SelectionSort.

Good, you defined int low and int high variables. But…

Ganado wrote:
What values are being passed to FindIndexOfSmallest()?

…now you never give them values! What is low supposed to be? 0? Assign it that. What is high supposed to be? 10? 10000? 7?

Last edited on

I have the following code, but when I run it, it glitches or something like that. I also have to include in both functions how many times the numbers are compared, but I do not know how to do that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

int main()
{

int FindIndexOfSmallest(int array[], int low, int high);
void SelectionSort(int array[], int size);
int A[] = {50, 30, 66, 10, 168, 45, 99, 20};
 FindIndexOfSmallest(A, 10, 168);
 SelectionSort(A, 8);
}
int FindIndexOfSmallest(int array[], int low, int high)
{
    low = 10;
    high = 168;
	int i, pos = low;
	for (i=low; i<=high; i++)
        {
	      if (array[i] < array[pos]) pos = i;
	    }
	return pos;
}
void SelectionSort(int array[], int size)
{
    int startScan, minIndex, minValue;

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++)
        {
            if (array[index] < minValue)
            {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

Hello Spiderman30,

Getting better, but still have some problems.

Lines 7 and 8 have defined «low» and «high» like you need. As is they are still a problem because they were not initialized so they have not value. On my computer a uninitialized int variable usually has the value of «-858993460» because if what is in the memory when that space was reserved. I tend to initialize variables like this int low{};. The empty {}s are called uniform initialization and is the simplest way to use. Also you can put a number inside the {}s if needed. Otherwise numeric variables are set to zero.

Lines 9 and 10 are proto types and are best put above «main».

Line 12 is an incorrect function call.
line 13 is the correct way.

Line 12 calls a function that returns a value, but you never collect that value that is returned in anything or make any use of it in any way like a «std:cout» statement.

The function «FindIndexOfSmallest» is defined correctly. The problems you will have is that «low» and «high» contain garbage values and thus the function will not work. Even when I gave values to those variables the function did not work the way you want. I had to rewrite the function.

The «SelectionSort» function is also defined correctly. As I recall it was the only part of the program that worked.

«FindIndexOfSmallest» is working on an unsorted array, but if you use this function before the sort function you will hae a problem with any output that comes after the «sort» function. If you put the «sort» function before the find function it makes the find function kind of pointless because the array has been sorted, so the first element of the aray is the lowest value.

Hope that helps,

Andy

«low» and «high» aren’t supposed to be the lowest and highest values in the array, they are meant to be the lowest and highest indices of the array, because you’re looping on (i=low; i<=high; i++).

1
2
3
4
int FindIndexOfSmallest(int array[], int low, int high)
{
    low = 10;
    high = 168;

You don’t need to re-assign low and high after you pass them in. That defeats the purpose of having function parameters.

Arrays start with index 0, and end with index num elements — 1. So in your case, your lowest index is 0, and your highest index is 7, because your array has 8 elements in it.

Call the function like FindIndexOfSmallest(A, 0, 7); and don’t re-assign the low and high variables inside the function itself.

Last edited on

Hello Spiderman30,

We are getting closer.

Refer to Ganado’s last post and think about this: Line 11 calls the function. Using hard coded numbers will work, but variables, in this case «low» and » high» should be what you use, because this gives the program more flexibility for the future. And less to change as you will see shortly. Also «low» and » high» is what should be passed to the function.

Consider this as a way of making the program easier to use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

//using namespace std;  // <--- Best not to use.

constexpr int MAXSIZE{ 8 };  // <--- As a global variable it is visible to the whole file.

int FindIndexOfSmallest(int array[], int low, int high);
void SelectionSort(int array[], int size);

int main()
{
	int array[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
	int low{}, high{ MAXSIZE };// <--- low is zero and high is 8.
	int pos{};

	SelectionSort(array, MAXSIZE);
	pos = FindIndexOfSmallest(array, low, high);

	std::cout << "n Lowest number is: " << array[pos] << std::endl;
	std::cout << "n Lowest number is: " << array[0] << std::endl;  // <--- Because the array is sorted with the lowest in element zero.

	return 0;  // <--- Not needed, but good programming.
}

Parts of this code make it easier to change just by changing the value of «MAXSIZE». This also makes he program more flexible. Notice how «low» and «high» are defined in main and passed to the function.

If lines 16 and 17 are reversed «pos» will have the correct value for an unsorted array, but will be incorrect when the array is sorted.

Hope that helps,

Andy

Hey Andy, nice comments. Not trying to confuse the OP, but one minor correction is to make high = MAXSIZE — 1 instead of MAXSIZE, because his for loop goes from low to high, inclusive.

Also, why do you say his FindIndexOfSmallest value works wrong when the array is sorted? There might be something I’m not seeing, but that function seems correct to me.

1
2
3
4
5
6
Let's do {1, 2, 3}                        '
  pos = 0
1. i = 0,  if (array[0] < array[0]) --> false
2. i = 1, if (array[1] < array[0]) --> false
3. i = 2, if (array[2] < array[0]) --> false
return pos; // 0 
1
2
3
4
5
6
Let's do {3, 1, 2}                        '
  pos = 0
1. i = 0,  if (array[0] < array[0]) --> false
2. i = 1, if (array[1] < array[0]) --> true, pos = 1
3. i = 2, if (array[2] < array[1]) --> false
return pos; // 1 

seems correct to me, whether unsorted or not.

Edit: Oooooh, I see what you’re saying. It’s not that the function is wrong, you’re just saying it’s pointless to find the min index right before sorting, because the index is invalidated by the sorting.
Yeah I agree. It’s a weird exercise for the OP, but he probably has to do it in that order for his assignment.

Last edited on

This is the assignment question in case it clears anything up: Write a program to sort the numbers in an array in descending order using both selection and bubble sorting methods. In both soring function, you are required to call a function to swap two elements of the array. Show the total number of comparisons and swaps in each sorting method. Also display the all the passes for each sorting method in an output file. Test your program with the array A = {50, 30, 66, 10, 168, 45, 99, 20},

If you post your progress again, following my and Andy’s suggestions, we can continue to help you.

First thing I notice is that your assignment never actually asks you to «find index of smallest», but you have a function defined to do so. Why?

Show the total number of comparisons and swaps in each sorting method.

You’ll want two counter variables inside each sorting method; increment the respective one after each comparison and each swap, then prints the totals at the end of the function.
But I personally wouldn’t worry about this until you know that your sorting algorithms are correct.

Here’s what my main function would look like, if this were my problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    constexpr int MAXSIZE = 8;
    int A[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
    int B[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };

    SelectionSort(A, 0, MAXSIZE-1);

    // print the sorted A array to make sure it's correct

    BubbleSort(B, 0, MAXSIZE-1); // you'll need to write this function eventually as well.

    // print the sorted B array to make sure it's correct

}

Last edited on

That was based off of example material for the BubbleSort, and the function was titled FindIndexOfSmallest. I guess I just forgot to change the function name to what it is actually representing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
int MAXSIZE{8};
int BubbleSort(int array[], int low, int high);
void SelectionSort(int array[], int size);
int main()
{
    int MAXSIZE = 8;
    int A[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
    int B[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };

    SelectionSort(A, 0, MAXSIZE-1);
    BubbleSort(B, 0, MAXSIZE-1);

}
int BubbleSort(int array[], int low, int high)
{
    low = 10;
    high = 168;
	int i, pos = low;
	for (i=low; i<=high; i++)
        {
	      if (array[i] < array[pos]) pos = i;
	    }
	return pos;
}
void SelectionSort(int array[], int size)
{
    int startScan, minIndex, minValue;
    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++)
        {
            if (array[index] < minValue)
            {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

Took your code and ran for any errors.

here is the code that compiled but did not output or print out any text.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;
int MAXSIZE{8};
int BubbleSort(int array[], int low, int high);
void SelectionSort(int array[], int size, int MAXSIZE);
int main()
{
    int MAXSIZE = 8;
    int A[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
    int B[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };

    SelectionSort(A, 0, MAXSIZE-1);
    BubbleSort(B, 0, MAXSIZE-1);

}
int BubbleSort(int array[], int low, int high)
{
    low = 10;
    high = 168;
	int i, pos = low;
	for (i=low; i<=high; i++)
        {
	      if (array[i] < array[pos]) pos = i;
	    }
	return pos;
}
void SelectionSort(int array[], int size, int MAXSIZE)
{
    int startScan, minIndex, minValue;
    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = startScan + 1; index < size; index++)
        {
            if (array[index] < minValue)
            {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

Hello Spiderman30,

Like sr2cute702 I took your code and made these changes before I could compile and run the program.

Read the comments in the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>

//using namespace std;  // <--- Best not to use this. No real need for it with what you have here.

constexpr int MAXSIZE{ 8 }; // <--- Needs to be a constant. Changed.

int BubbleSort(int array[], int low, int high);
void SelectionSort(int array[], int size);

int main()
{
	//constexpr int MAXSIZE = 8;  // <--- Not needed here with the global variable.

	int A[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
	int B[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };

	SelectionSort(A, 0, MAXSIZE - 1);  // <--- Sending 3 parameters, but calls for two.
	BubbleSort(B, 0, MAXSIZE - 1);

}

int BubbleSort(int array[], int low, int high)
{
	// Next two lines not needed. Values passed in from function call. Those should be used.
	low = 10;
	high = 168;
	int i, pos = low;

	for (i = low; i <= high; i++)  // <--- Will loop 158 times, but the array has a size of 8. Most of the
	{                              //  loop will be outside of the boundry of the array and "low" should
		                       //  start at zero not 10. Even 10 is outside the boundary of tha array.
		if (array[i] < array[pos]) pos = i;
	}
	return pos;
}

//  Have not tested the selection sort yet. I do believe that it looks like your last version which did work.
void SelectionSort(int array[], int size)
{
	int startScan, minIndex, minValue;

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		minValue = array[startScan];
		for (int index = startScan + 1; index < size; index++)
		{
			if (array[index] < minValue)
			{
				minValue = array[index];
				minIndex = index;
			}
		}

		array[minIndex] = array[startScan];
		array[startScan] = minValue;
	}
}

I will know more once I have chance to test the program.

Hope that helps,

Andy

Hello Spiderman30,

After testing the program the «SelectionSort» function works, but the «BubbleSort» function is not a bubble sort it just returns the index of the lowest value. Not what you want.

Also changed the function call to just using «MAXSIZE» as the third parameter and changed the for loop condition to just be «<» instead of «<=».

Hope that helps,

Andy

@ Ganado,

Not trying to confuse the OP, but one minor correction is to make high = MAXSIZE — 1 instead of MAXSIZE, because his for loop goes from low to high, inclusive.

Actually the better solution is not to use «<=» in the for loop, but to use «<» only, Much less confusing this way.

Also, why do you say his FindIndexOfSmallest value works wrong when the array is sorted? There might be something I’m not seeing, but that function seems correct to me.

Maybe it was me when I first ran the original code I was getting the wrong answer. This could have been from other parts not being set up correctly. Even on the latest revision I had to make some changes to make it work.

Thank you for the input it keeps me on my toes and thinking.

Andy

Last edited on

I thought I fixed the BubbleSort function but it is still giving me a hard time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>

const int MAXSIZE{ 8 };

int BubbleSort(int array[], int N);
void SelectionSort(int array[], int size);

int main()
{
	int A[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };
	int B[MAXSIZE] = { 50, 30, 66, 10, 168, 45, 99, 20 };

	SelectionSort(A, 0, MAXSIZE - 1);
	BubbleSort(B, 8);

}
int BubbleSort(int array[], int N)
{
	int temp;
	bool Swap
    do
    {
        swap = false;
        for (int count = 0; count < (N - 1); count++)
        {
            if (array[count] > array[count++])
            {
                temp = array[count];
                array[count] = array[count + 1];
                array[count + 1] = temp;
                Swap = true;
            }
        }
    }while (swap);
}
void SelectionSort(int array[], int size)
{
	int startScan, minIndex, minValue;

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		minValue = array[startScan];
		for (int index = startScan + 1; index < size; index++)
		{
			if (array[index] < minValue)
			{
				minValue = array[index];
				minIndex = index;
			}
		}

		array[minIndex] = array[startScan];
		array[startScan] = minValue;
	}
}

Pages: 12

uint8_t *mmac_source1 = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x01 }; 

Here you don’t memory allocated to the pointer.mmac_source1 just acts as a place holder wherein you can store an address.

uint8_t mmac_source1[6] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x01 };

Here you have an array where in your compiler allocates sizof(uint8_t)*6 bytes.


In many instances a pointer is interchangable with an array. More formally it can be said that the first element of an array decays to a pointer.

But there are exceptions and the one you cite in your question is one of them: uint8_t *mmac_source1 = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x01 }; is not syntatically valid. Conceptually you are allocating, in your second case, the array on the stack. Using a pointer in that instance doesn’t make sense.


The rvalue expected for a pointer initialization is a memory address.

As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared:

char * str = "hello"; // what succeeds the equal to is the rvalue.

The above statement is similar to

char str[] = "hello";

The next question is if we are allowed to do the following :

int* v = 2;

Yes we are but at our own risk. The compiler will initially come withan error:

error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]

Here the compiler considered the rvalue as merely an integer where what it expected was a memory location say for example &a or so. At the same timeit provided an option fpermissive to overrride its assumption wherebywe can force the rvalue to look like a memory address.fpermissive flagdowngrades some diagnostics about nonconformant code from errors to warnings. So when compiling, I did

g++ -fpermissive intpointerexample.cpp -o intpointerexample

Eventually on executing intpointerexample, I encountered a segmentation fault because I might have attempted to access memory the program does not have rights to.


Инициализируйте свой вектор в цикле, например:

for(int i = 1; i <= 6; ++i)
  v.push_back(i);

Как показывает cdhowie, ваша версия gcc не поддерживает список инициализаторов (вам нужна хотя бы версия g++ версии 4.4, ). Если вы приобретете новый (добавив флаг -std=c++0x или -std=gnu++0x), вы увидите следующее:

std::vector<int> v = {1,2,3,4,5,6};

или

Если вы хотите сделать это с помощью списка инициализаторов, вы должны использовать std:: initializer_list следующим образом:

#include <iostream>
#include <vector>
#include <initializer_list>

template <class T>
struct S {
    std::vector<T> v;
    S(std::initializer_list<T> l) : v(l) {
         std::cout << "constructed with a " << l.size() << "-element listn";
    }
    void append(std::initializer_list<T> l) {
        v.insert(v.end(), l.begin(), l.end());
    }
    std::pair<const T*, std::size_t> c_arr() const {
        return {&v[0], v.size()};  // list-initialization in return statement
                                   // this is NOT a use of std::initializer_list
    }
};

template <typename T>
void templated_fn(T) {}

int main()
{
    S<int> s = {1, 2, 3, 4, 5}; // direct list-initialization
    s.append({6, 7, 8});      // list-initialization in function call

    std::cout << "The vector size is now " << s.c_arr().second << " ints:n";

    for (auto n : s.v) std::cout << ' ' << n;

    std::cout << 'n';

    std::cout << "range-for over brace-init-list: n";

    for (int x : {-1, -2, -3}) // the rule for auto makes this ranged for work
        std::cout << x << ' ';
    std::cout << 'n';

    auto al = {10, 11, 12};   // special rule for auto

    std::cout << "The list bound to auto has size() = " << al.size() << 'n';

//    templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression,
                             // it has no type, and so T cannot be deduced
    templated_fn<std::initializer_list<int>>({1, 2, 3}); // OK
    templated_fn<std::vector<int>>({1, 2, 3});           // also OK
}

Источник

Понравилась статья? Поделить с друзьями:
  • Error saving settings file jbridge
  • Error saving file aseprite
  • Error saving changes make sure toggle hd mode is run as administrator
  • Error saving build prop что делать
  • Error saving account mysql workbench