Bug
今天在做leetcode两数之和时,想要完整地实现整个程序,于是写了头文件
//twoSum.h #ifndef TWO_SUM_H_ #define TWO_SUM_H_ class Solution{ public: Solution(); std::vector<int> twoSum(std::vector<int> &nums, int target); ~Solution(); };
和main文件
#include <iostream> #include <vector> #include <unordered_map> #include "twoSum.h" using namespace std; vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hash; vector<int> vec; //如果这里的i不用unsigned int类型,gcc编译器会出一个warning for(unsigned int i=0;i!=nums.size();++i) { int temp = target - nums[i]; if(hash.find(i)!=hash.end()) { vec.push_back(i); vec.push_back(temp); break; } vec[i] = i; } return vec; } int main(){ Solution s; vector<int> nums{2,7,11,15}; int target = 9; vector<int>* p = &s.twoSum(nums, target); for(vector<int>::iterator iter=p->begin();iter!=p->end();++iter) cout<< *iter <<endl; return 0; }
g++ -std=c++11 main.cpp -Wall
发现报错main.cpp: In function ‘int main()’:
main.cpp:31:44: error: taking address of temporary [-fpermissive] vector<int> *p = &s.twoSum(nums, target);
原因
去StackOverflow看了一下
https://stackoverflow.com/questions/16481490/error-taking-address-of-temporary-fpermissive
原来是是C++不允许对一个临时变量进行取地址操作,为什么会产生一个临时变量呢?
原来,在类里面没有定义