I've just started learning C++ and am complete newbie, sorry in advance if the question will sound stupid
I have my program to solve Two Sum problem:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(const vector<int>& a, int target) {
unordered_map<int, int> valueToIndex;
for (int i = 0; i < (int)a.size(); i++) {
auto it = valueToIndex.find(target - a[i]);
if (it != valueToIndex.end()) {
return { it->second,i };
}
valueToIndex[a[i]] = i;
}
throw invalid_argument("sum not found");
}
};
int main()
{
vector<int> a{ 11,22,33,44,55 };
int target_value = 55;
Solution A;
A.twoSum(a,target_value);
return 0;
}
When I try to compile my program using test input values console returns nothing
What could be the issue?
Thanks!
Firstable, if you have a function that returns something, you need to get that return.
In your example, like that
vector<int> myResult = A.twoSum(a,target_value);
Then you can use that result like that.
for (const auto &value : myResult)
std::cout << value << std::endl;
Related
I have a piece of c++ code:
#include <iostream>
#include <string>
#include <map>
static counter = 0;
class Probe
{
private:
int supply_;
Probe(const Probe&);
public:
Probe()
{
supply_ = 10000;
}
int get_supply()
{
return supply_;
}
};
/********************************************************************************
template<class T> T Create(int counter, T& produced)
{
produced[counter] = new ; // ??????????????????????????????????????
return produced;
}
************************************************************************************/
std::map<int, Probe*> CreatInitWorkers(int counter, std::map<int, Probe*> &init_workers)
{
init_workers[counter] = new Probe();
return init_workers;
}
int main()
{
std::map<int, Probe*> workers;
for (int i = 0; i < 12; i++)
{
workers = CreatInitWorkers(worker_counter++, workers);
}
for (auto it : workers)
{
std::cout << it.first << std::endl;
}
}
I want to create a template function (as it shows between the stars) like the CreatInitWorkers function. But I don't know how to transfer the Probe class to the new operation because for my program there are still other classes needed to be there. Is there any way can do it? Thanks.
Something along these lines:
template<class T> T Create(int counter, T& produced)
{
using C = std::remove_pointer_t<std::decay_t<decltype(produced[counter])>>;
produced[counter] = new C();
return produced;
}
Demo
Im trying to write a adjacency matrix representation using vectors of integer vectors , therefore vector> . However when I add members to the vector and later try and print those values nothing has changed. Most likely it has to do with "pass by value" however I have used "pass by reference" to the best of my knowledge.
Here is my header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight);
void print_graph();
private:
std::vector<std::vector<int>> vertex_matrix;
int num_of_vertices;
int num_of_edges;
};
#endif
the cpp implementation file:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices)
{
if (_num_of_vertices==0)
{
_num_of_vertices=10;
}
for (int i = 0; i < _num_of_vertices; i++)
{
vertex_matrix.push_back(vector<int> (_num_of_vertices,INT_MAX));
}
}
graph::~graph()
{
vertex_matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight)
{
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
}
void graph::print_graph()
{
for (int i=0; i< vertex_matrix.size(); i++)
{
for (int j = 0; j < vertex_matrix.size(); j++)
{
//vertex_matrix[i][j]
std::vector<int> columnVector = vertex_matrix[i];
if (columnVector[j] != INT_MAX)
{
std::cout << columnVector[j] ;
}
else
{
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
the main entry:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
_graph.add_edge(1,2,1);
_graph.add_edge(2,3,1);
_graph.add_edge(3,1,1);
_graph.add_edge(3,3,1);
_graph.add_edge(3,4,1);
_graph.add_edge(4,0,0);
_graph.print_graph();
}
When I use the print function I currently getting 0's.
How can I make this proper pass by reference, and have the updated values print.
Thanks
As stated in the comments, you are creating a copy of your column and then modifying the copy. What you want to do is to make a reference to it.
vector<int>& columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
Or you can access the element directly.
if (vertex_matrix[v1-1][v2-1] == INT_MAX)
{
vertex_matrix[v1-1][v2-1] = weight;
}
In print_graph you are doing the same, but here you are not modifying anything so that works, but you are making an unnecessary copy for no reason which is not ideal.
A last point is that you are calling vertex_matrix.clear() in your destructor. This is redundant, when the vector goes out of scope it will clear itself up, so you don't need to manage that.
I'm working with c++ STL vectors, and have a vector of structures called projectileList. I'm trying to iterate through the vector, getting and setting values in the struts as I iterate, but my code refuses to compile, with the error 'Incomplete type is not allowed.'
Can anyone please point out what I'm doing wrong:
Code:
ProjectHandeler.h:
#include "stdafx.h"
#include "DataTypes.h"
#include <vector>
class ProjectileHandeler {
private:
int activeObjects;
std::vector<projectile> projectileList;
void projectileUpdater();
public:
ProjectileHandeler(projectile* input[], int projectileCount);
~ProjectileHandeler();
};
#endif
projectileHandeler.cpp
#include "stdafx.h"
#include "DataTypes.h"
#include "ProjectHandeler.h"
#include <vector>
ProjectileHandeler::ProjectileHandeler(projectile* input[], int projectileCount)
{
for (int i = 0; i < projectileCount; i++)
{
projectileList.push_back(*input[i]);
activeObjects += 1;
}
//NO extra slots. Not that expensive.
projectileList.resize(projectileList.size());
}
void ProjectileHandeler::projectileUpdater()
{
while (true)
{
for (unsigned int i = 0; i < projectileList.size(); i++)
{
if (projectileList[i].isEditing == true)
break;
}
}
}
This compiles fine (tested it here: http://codepad.org/cWn6MPJq):
#include <vector>
struct projectile {
bool isEditing;
};
class ProjectileHandeler {
private:
std::vector<projectile> projectileList;
void projectileUpdater()
{
//This bit loops to infinity and beyond! ...or at least untill the handeler is destroyed.
while (true)
{
for (unsigned int i = 0; i < projectileList.size(); i++)
{
if (projectileList[i].isEditing == true) //Throws Incomplete type error
break;
}
}
}
};
int main()
{
}
Notice the removal of *, correct type of loop variable and removal of extra class specifier.
unique is not working pls help
its showing compiler error
I tried making it a
set<str> se(ss.begin(), ss.end());
ss.assign(se.begin(), se.end());
I tried this too and it also shows compiler error
Is it because of the bool sortByString()
I saw that code in a page so that it helps to sort a vector class objects
if there is any other way pls help
#include <cmath>
#include<set>
#include <cstdio>
#include <vector>
#include <iostream>
#include<string>
#include <algorithm>
using namespace std;
int n;
class str
{
public:
string a;
void in(string s)
{
a=s;
}
string get(){
return a;
}
void out()
{
cout<<a;
}
};
bool sortByString(str &t1, str &t2)
{
return t1.get() < t2.get();
}
string d(vector<str> a)
{
string s;
for(int i=0;i<n;i++)
s.append(a[i].get());
return s;
}
int main() {
string s,sub;
cin >> s;
int length = s.length();
int i, k = 0, c;
vector<str> ss;
str a;
n = length*((length + 1) / 2);
k = 0;
for (c = 0; c < length; c++)
{
for (i =length-c;i>=1; i--)
{
a.in(s.substr(c,i));
ss.push_back(a);
}
}
s=" ";
ss.erase(unique(ss.begin(),ss.end()),ss.end()); /*code giving compiler error pls help*/
s=d(ss);
cout<<s;
return 0;
}
You are missing operator== in str. std::unique requires this operator.
class str
{
//....
bool operator==(const str& rop) const {
return a == rop.a;
}
};
bool sortByString(str &t1, str &t2)
bool sortByString(const str &t1, const str &t2)
At least for g++. VS will compile any, as I think.
I've been recently working on a program which consists basically of 24 variations of one function(below). Everything gets executed perfectly apart from the part where I try to compare functions(with eachother). I found out that it is possible to be done by writing 24 if-else statements, yet I am certain there is a shorter way. I've also tried with vectors but no luck for now. Thanks for any help!
one of 24 functions:
int funk1()
{
ifstream myfile ("file.txt");
string line;
int i;
class1 obj1;
obj1.atr1= "Somename";
obj1.atr2="GAATTC";
while (getline(myfile, line))
{
i = countSubstring(line, obj1.atr2);
obj1.sum += i;
};
cout<<obj1.sum<<": "<<obj1.atr1<<"\n";
return obj1.sum;
}
The main function:
int main(){
funk1();
funk2();
funk3();
funk4();
funk5();
funk6();
funk7();
funk8();
funk9();
funk10();
funk11();
funk12();
funk13();
funk14();
funk15();
funk16();
funk17();
funk18();
funk19();
funk20();
funk21();
funk22();
funk23();
funk24();
//This is one way to do it
if (funk18() > funk1())
{
cout<<funk18<<" is the biggest";
}
//...
}
Here is a clean and elegant c++11 solution:
#include <iostream>
#include <functional>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
using MyFunc = std::function<int()>;
int f1() { return 1; }
int f2() { return 15;}
int f3() { return 3; }
int main() {
std::vector<MyFunc> my_functions = {f1, f2, f3};
int max = std::numeric_limits<int>::min();
for (auto const &f : my_functions) {
max = std::max(max, f());
}
cout << max << endl;
return 0;
}
if you want to store the results from functions instead, you could do:
std::vector<int> my_results;
my_results.reserve(my_functions.size());
for (auto const &f : my_functions) {
my_results.push_back(f());
}
auto max_it = std::max_element(std::begin(my_results), std::end(my_results));
cout << *max_it << endl;