Long story short. Im trying to run this code in VS Studio IDE.
#include <iostream>
#include <vector>
using std::vector;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
return {i, j};
}
}
}
return {};
}
};
I had to add #include to get the first problem resolved. But now its saying:
using-declaration for non-member at class scope
expected unqualified-id before '<' token
The plot thickens. It runs fine on leetcode without the #include . None of this transpires.
Is it a vector issue or what? And why does VS Studio code hate this but it runs fine on leetcode? https://leetcode.com/problems/two-sum/solutions/1439021/c-brute-force-hashmap-solutions/?q=brute&orderBy=most_votes&languageTags=cpp
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
return {i, j};
}
}
}
return {};
}
};
OG code.
Thanks in advance.
Although I would NOT recommend the use of using
at header level because of namespace clashes, if you really want to use it, consider the version below:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
return {i, j};
}
}
}
return {};
}
};
That said, most people would agree that the approach below looks more "modern"
#include <iostream>
#include <vector>
#include <tuple>
#include <optional>
class Solution {
public:
std::optional< std::tuple<int,int> > twoSum( const std::vector<int>& nums, int target) {
for( int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if( nums[i] + nums[j] == target){
return {{i, j}};
}
}
}
return {};
}
};
int main() {
std::vector<int> vec{1,2,3,4};
int total = 5;
Solution s;
auto result = s.twoSum( vec, total );
if ( result ) {
auto [i,j] = result.value();
std::cout << vec[i] << " + " << vec[j] << " = " << total << std::endl;
}
}