试图对动态数组sum_array进行排序,但该功能无法正常工作。如果我不将array的大小设置为1,我的循环也会自终止,这样我的声明就可能有问题
**#include<bits/stdc++.h>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
vector <int> sum_array (1);
int n;
cin>>n;
int sum,marks;
for (int i = 0; i < 5; i++) {
cout<<"turn now is ="<<i<<endl;
sum=0;
for (int k = 0; k < (n-1); k++) {
cin>>marks;
sum=sum+marks;
cout<<"sum="<<sum<<endl;
}
sum_array[i]=sum;
}
for (int i = 0; i < 5; i++) {
cout<<sum_array[i]<<endl;
}
sort(sum_array.begin(),sum_array.end());
cout<<"after"<<endl;
for (int i = 0; i < 5; i++) {
cout<<sum_array[i]<<endl;
}
return 0;
}**
答案 0 :(得分:2)
您正在创建一个整数的向量:
Global variables in header file :
#define TRUE 1
#define FALSE 0
int finished = FALSE
pthread_cond_t qServiced = PTHREAD_COND_INITIALIZER;
pthread_cond_t qEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t qElement = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
Create 1 writer thread
Create 2 reader threads
Writer join <- Success
Reader join <- Program hangs here
void* writer()
{
int totalQueued = 0;
int tasks = 20;
while(!finished)
{
pthread_mutex_lock(&mutex);
while(isFull(q))
{
pthread_cond_wait(&qEmpty, &mutex);
}
if(totalQueued < tasks)
{
for(j = 0; j < 2; j++) //Add 2 numbers at a time
{
if(!(isFull(q)))
{
//Assume random numbers added to queue
totalQueued++;
}
}
pthread_cond_signal(&qElement);
pthread_cond_wait(&qServiced, &mutex);
}
else
{
finished = TRUE;
}
pthread_mutex_unlock(&mutex);
}
//Thread exits
}
void* reader()
{
while(!finished)
{
pthread_mutex_lock(&mutex);
while(isEmpty(q)) //If the queue is empty
{
pthread_cond_signal(&qEmpty);
pthread_cond_wait(&qElement, &mutex);
}
int n = dequeue(q);
printf("%d\n", n);
pthread_cond_signal(&qServiced); //Signal that task has been serviced
pthread_mutex_unlock(&mutex);
}
}
然后,您将访问元素超出向量的范围(这是未定义的行为)。
std::vector<int> sum_array(1);
for (int i = 0; i < 5; i++) {
// ...
sum_array[i] = sum;
}
仅对一个元素的向量进行排序,因此它什么也没做。
由于您不知道向量的大小,因此应将其初始化为空向量:
std::sort
并将元素推入std::vector<int> sum_array;
:
sum_array