Issues with std::runtime_error?

Hi,
I keep getting an error saying "terminate called after throwing an instance of 'std::runtime_error'
what(): The vector can't be empty!
"

Then, my executable file stops working.

I think the error is in my function for overloading the right stream operator since I get the error after my output prints "Right stream works for single value!"
I'm not comfortable with std::runtime_error yet, so I'm having a lot of trouble trying to figure out what my problem is.
Any help would be much appreciated.


chai_test.cpp
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
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>

using std::vector;

int main(int argc, char** argv) {
//Testing operator>>
	std::vector<int> test_right_stream;
	int out1, out2, out3;
	test_right_stream << 10;
	test_right_stream >> out1;
	if (10 == out1) {
		std::cout<<"Right stream works for single value!\n";
	}
	else {
		std::cout<<"Right stream fails for single value!\n";
	}
	//Should throw an exception
	try {
		test_right_stream >> out1;
		std::cout<<"Right stream didn't throw an exception when the vector was empty!\n";
	}
	catch (std::runtime_error) {
		std::cout<<"Right stream throws exception when vector is empty!\n";
	}
return 0;
}



chai.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef CHAI_H
#define CHAI_H

#include <vector>
#include <iostream>

using namespace std;

vector<int>& operator<<(vector<int>&, int);


std::vector<int>& operator>>(vector<int>& v, int& x);


#endif 



chai.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>

using std::vector;

vector<int>& operator<<(vector<int>& v, int x){	
	v.push_back(x);
	return v;
}

vector<int>& operator>>(vector<int>& v, int& x){

	if(v.empty()){
		throw std::runtime_error("The vector can't be empty!");	
	}
	x = v.back();
	v.pop_back();

	return v;

}
I've tried your code and it works as intended :

http://coliru.stacked-crooked.com/a/e8bf5042e60f1a74

are u sure that is exactly the code
Hm, I think something might just be wrong with my compiler because I tried running it in Ubuntu using virtualbox and it also ran smoothly.
Last edited on
Topic archived. No new replies allowed.