为什么temp在捕获到第一个异常后外部变成空的?
#include <iostream>
int main()
{
std::string temp("exception");
int value;
while(std::cin>> value && value != 0)
{
try{
if(value > 9) throw temp;
else std::cout << value << "\n";
}
catch(std::string temp)
{
std::cout << temp << "\n";
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入:
1
2
11
13
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
exception
// Printing Empty string
Run Code Online (Sandbox Code Playgroud)
预期产量:
1
2
exception
exception
Run Code Online (Sandbox Code Playgroud)
我使用g ++ 7.3.0编译代码。
为什么STL排序不适用于map <int,vector <int>>?
我是否缺少某些东西,或者我是否需要进行类似比较功能的排序。任何人都可以提出一些想法。
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
int main(){
std::map<int,std::vector<int>> map1;
map1[0].push_back(3);
map1[0].push_back(2);
map1[0].push_back(1);
map1[1].push_back(3);
map1[1].push_back(2);
map1[1].push_back(1);
for(auto i : map1){
std::cout<< i.first << " --> ";
for(auto j : i.second){
std::cout<<j<<" ";
}
std::cout<<"\n";
}
for(auto i : map1){
std::sort(i.second.begin(), i.second.end());
}
std::cout<<"\n";
for(auto i : map1){
std::cout<< i.first << " --> ";
for(auto j : i.second){
std::cout<<j<<" ";
}
std::cout<<"\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
排序前后的输出相同。
0-> 3 2 1
1-> 3 2 1
在此运算符重载代码中,我不想在需要的地方写“ using namespace std”,而是想包含“ std ::”。
在cout和cin之后添加“ std ::”后,我仍然在其他包含“ std ::”的地方出现错误。
#include<iostream>
//using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
friend ostream & operator << (ostream &, const Complex &);
friend istream & operator >> (istream &, Complex &);
};
ostream & operator << (ostream &out, Complex &obj)
{
out<<obj.real<<" "<<obj.imag;
return out;
}
istream & operator >> (istream &in, const Complex &obj)
{
in>>obj.real>>obj.imag; …Run Code Online (Sandbox Code Playgroud)