class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
int k=0;
int m=nums1.size();
int n=nums2.size();
vector<int> res[m];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(nums1[i]==nums2[j]){
res[k]=nums1[i];
k++;
break;
}
}
}
return res;
}
};
I had to find duplicates in two different arrays and return the same. But I'm getting the error
no viable overloaded '='
from the compiler in the line where I am storing my duplicates in the res[k] vector.
In this line you try to allocate an array of std::vectors.
vector<int> res[m];
But m is not constant so it causes a compilation error (C++ does not support VLA - see Why aren't variable-length arrays part of the C++ standard?).
I am not sure what exactly you are trying to do, but I believe you should change it to:
vector<int> res;
Then use push_back to add elements to it:
res.push_back(nums1[i]); // Instead of: res[k]=nums1[i];
You don't need to track the number of elements in the vector with k and you can eliminate it altogether.
2 more notes:
The method intersect can be a static method (or a free functions) as it doesn't need access to any class members.
Your algorithm implementation compares each element in nums1 to each element in nums2 so you will get duplicates in the output array (not sure what was intended).
Related
I made a vector of vectors and i wanted to take values from the user.I simply don't know what is the problem with it
why can't i use push_back() here
and if you have any other method than this please tell.
vector<vector<int>> v;
for(int i=0;i<n;i++)
{
v.push_back(i+1);
for(int j=0;j<n;j++)
{
v[i].push_back(j+1);
}
}
doing this gives me error
error: no matching function for call to 'std::vector<std::vector<int> >::push_back(int)'
v.push_back(i+1);
You declared a vector of vectors of the type std::vector<std::vector<int>>.
vector<vector<int>> v;
It means that elements of the vector v has the type std::vector<int> not int.
So the compiler issues an error message for this statement
v.push_back(i+1);
that does not make a sense.
You could use such a call provided that the class template std::vector had an implicit constrictor from an integer expression to the type std::vector. However such a constructor is explicit
explicit vector(size_type n, const Allocator& = Allocator());
Thus there is no implicit conversion from the parameter an expression supplied to the parameter n to the type std::vector<int>.
It seems you mean the following
vector<vector<int>> v;
for(int i=0;i<n;i++)
{
v.resize(i+1);
for(int j=0;j<n;j++)
{
v[i].push_back(j+1);
}
}
It is because v is a vector containing a vector of ints. Meaning you can't push_back an integer as it wants an int vector.
vector<vector<int>> v;
for(int i=0;i<n;i++)
{
vector<int> v2;
for(int j=0;j<n;j++)
{
v2.push_back(j+1);
}
v.push_back(v2);
}
Now consider this code, it will work because you are creating a new vector of ints, v2. If you push v2 to v, it will work as v requires an int vector for push_back.
People like to overcomplicate things when answering. The idea here is that you have created a vector inside a vector. So the first vector takes a vector as an input, whereas the second vector takes an "int". Therefore, you shouldn't push an integer in the first vector but a VECTOR of integers.
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > result;
vector<int> sofar;
permutehelper(nums, sofar, result);
return result;
}
void permutehelper(vector<int> &rest, vector<int> &sofar, vector<vector<int>> &ans){
if(rest.size() == 0) {
ans.push_back(sofar);
}
else{
for(int i = 0; i < rest.size(); i++){
sofar.push_back(rest[i]);
rest.erase(rest.begin() + i);
permutehelper(rest, sofar, ans);
}
}
}
};
How do I modify it to return all permutation, Currently it is giving only [[1,2,3]]. I know there are many solutions but I want to make it work using vectors sofar and rest.
You only have one rest vector (and only one sofar vector) because you are passing by reference. That means that when you remove an element from rest, it's gone. You never put it back, so it's gone forever. (In fact, you're removing elements from the vector passed as an argument to permute. Some would say that modifying the argument is poor interface design.)
You probably want to pass the parameter vectors by value (other than ans, which accumulates results and thus should be permanently modified). Of course, passing by value makes copies, which introduces an unnecessary quadratic complexity, but it will allow the algorithm to work as expected.
#include<bits/stdc++.h>
using namespace std;
class Heap
{
vector <int> v;
int length;
public:
void create(vector <int> v, int s);
void display();
};
void Heap::create(vector <int> v, int s)
{
length=s+1;
for(int i=1;i<=s;i++)
{
this->v[i]=v[i-1];
}
int temp;
int j;
for(int i=2;i<length;i++)
{
temp=v[i];
j=i;
while(j>1&&temp>v[j/2])
{
swap(v[j],v[j/2]);
j=j/2;
}
if(j==1)
{
v[j]=temp;
}
}
}
void Heap::display()
{
for(int i=1;i<length;i++)
{
cout<<v[i]<<"\t";
}
cout<<endl;
}
int main()
{
vector <int> v;
int ans=1;
int d;
while(ans==1)
{
cout<<"Enter the Data\n";
cin>>d;
v.push_back(d);
cout<<"Do you want to enter more data?\n";
cin>>ans;
}
cout<<endl;
Heap h;
h.create(v,((int)v.size()));
h.display();
}
When i execute this code, it asks me to enter the data value. i enter all the data values i want to enter and click the enter button. it shows segmentation error. also the execution is taking a lot of time which is very unusaul. i use codeblocks version 20.
When i execute this code, it asks me to enter the data value. i enter all the data values i want to enter and click the enter button
Yeah, I'm not interested in guessing what you typed in order to reproduce your problem. I'm also not interested in guessing whether the issue is in your I/O code or the code you think you're testing.
Always remove interactive input when you're preparing a minimal reproducible example so that other people can actually reproduce it.
Sometimes removing the interactive input may fix your problem, in which case you've learnt something important (and probably want to ask a different question about your input code).
it shows segmentation error
A segmentation fault interrupts your program at the exact point where it happens. If you run your program in a debugger, it will show you where this is, and the state of everything in your program when it happened. You should try this, and learn to use your debugger.
this->v[i]=v[i-1];
As correctly pointed out in the other answer, there is a bug on this line.
You correctly called push_back when reading input, so you could just do the same here. Alternatively you need to explicitly size this->v before indexing elements that don't exist.
The other main problem with this function is that it mixes up this->v (used, illegally, only once on the line above) and v which is a local copy of the v in main, and which goes out of scope and is lost forever at the end of the function.
Just give your variables different names so you don't have to write this->v on all the other lines where you currently refer to v. Also, consider passing the original v by const ref instead of making a copy.
NB. I do see and understand that you're deliberately switching to 1-based indexing for the sort. If for some reason you can't just use std::sort or std::make_heap, you could at least explicitly set the zeroth element to zero, and then just std::copy the rest.
Finally, Heap::create really looks like it should just be a constructor. Forcing two-phase initialization is poor style in general, and I don't see any reason for it here.
First issue: you have used 'this->v' before initializing it. In this point:
this->v[i]=v[i-1];
this->v have size 0 and has no element to be accessed via index;
Furtheremore you have used wrong indices for it. Assuming this->v has initialized, correct index access is like this
this->v[i-1]=v[i-1];
Finally, it is better to sort the std vectors by using std::sort builtin function:
#include <algorithm>
std::sort(this->v.begin(), this->v.end());
This is obviously a school exercise. So I will only give you pointers as to where your code goes wrong.
class Heap
{
// vector <int> v; // v is not a suitable name for a class member, it's too short
// int length; // why length ? Your container declared above has length information, using
// a duplicate can only introduce opportunities for bugs!!!
vector<int> heap; // I've also renamed it in code below
public:
void create(vector <int> v, int s);
void display();
};
// some documentation is needed here...
// A I read it, it should be something like this, at least (this may reveal some bug):
//
// Initializes heap from range [v[1], v[s])
// void Heap::create(vector <int> v, int s) // you do not need a copy of the source vector!
void Heap::create(const vector& <int> v, int s) // use a const reference instead.
{
// This is not how you assign a vector from a range
// length=s+1;
// for(int i=1;i<=s;i++)
// {
// this->v[i]=v[i-1];
// }
// check inputs always, I'll throw, but you should decide how to handle errors
// This test assumes you want to start at v[1], see comment below.
if (0 > s || s >= v.size())
throw std::out_of_range ("parameter 's' is out of range in Heap::Create()");
// assign our private storage, why the offset by '1' ????
// I doubt this is a requirement of the assignment.
heap.assign(v.begin() + 1, v.begin() + s + 1);
//int temp; // these trivial variables are not needed outside the loop.
//int j;
// why '2' ?? what happens to the first element of heap?
// shouldn't the largest element be already stored there at this point?
// something is obviously missing before this line.
// you'll notice that v - the parameter - is used, and heap, our
// private storage is left unchanged by your code. Another hint
// that v is not suitable for a member name.
for(int i = 2; i < v.length(); i++)
{
int temp = v[i]; // temp defined here
int j = i;
//while(j > 1 && temp > v[j/2]) // avoid using while() when you can use for().
//{
// swap(v[j],v[j/2]);
// j=j/2;
//}
// This is your inner loop. it does not look quite right
for (; j > 1 && temp > v[j / 2]; j = j / 2)
swap(v[j], v[j/2]);
if (j == 1)
v[j] = temp;
}
}
void Heap::display()
{
for(int i=1;i<length;i++)
{
cout<<v[i]<<"\t";
}
cout<<endl;
}
From reading your code, it seems you forgot that vectors are zero-based arrays, i.e. The first element of vector v is v[0], and not v[1]. This creates all kinds of near unrecoverable errors in your code.
As a matter of personal preference, I'd declare Heap as deriving publicly from std::vector, instead of storing data in a member variable. Just something you should consider. You could use std::vector<>::at() to access and assign elements within the object.
As is, your code will not function correcly, even after fixing the memory access errors.
I was doing a problem on TopCoder for finding the longest path in an acyclic directed graph. I have used vector of type bool for visiting vertices. But it is giving me these errors (highlighted in the code below):
error: no match for ‘operator=’ (operand types are ‘std::vector<bool>’ and ‘bool’)
visited[cur_ver]=true;
error: no match for ‘operator==’ (operand types are ‘std::vector<bool>’ and ‘bool’)
if(visited[i]==false)
Here is my code:
#include<bits/stdc++.h>
using namespace std;
class Circuits{
vector<int>adj[51];
vector<int>cost[51];
vector<int>T[51];
vector<bool>visited[51];
vector<int>dist[51];
int glm=0;
public:
void topological_sorting(int cur_ver,int n){
visited[cur_ver]=true; //error 1
for(int i=0;i<adj[cur_ver].size();i++){
if(visited[i]==false) //error 2
topological_sorting(i);
}
T.insert(T.begin(),cur_ver);
}
void Longest_Path(int s,int n){
for(int i=0;i<=n;i++)
dist[i]=NINF;
dist[s]=0;
for(int i=0;i<=n;i++){
int u=T[i]
if(dist[u]!=NINF)
for(int j=0;j<adj[i].size();j++){
int v=adj[u][j];
if(dist[v]<dist[u]+cost[u][v])
dist[v]=dist[u]+cost[u][v];
}
}
for(int i=0;i<=n;i++)
if(dist[i]>glm)
glm=dist[i];
}
int howLong(vector<string>connects,vector<string>costs){
for(int i=0;i<connects.size();i++){
for(int j=0;j<connects[i].size();j++){
adj[i].push_back(int(connects[i][j]));
cost[i].push_back(int(costs[i][j]));
}
}
int n=connects.size();
for(int i=0;i<=n;i++)
visited[i]=false;
topological_sorting(0,n);
int lm=0;
for(int i=0;i<=n;i++){
Longest_Path(i,n);
if(glm>lm)
lm=glm;
glm=0
}
return lm;
}
};
You are confusing built-in array syntax and syntax of the std::vector<T> class. Precisely, with
std::vector<int> myVec[51]
you declare and array of 51 vectors of type int. Thus, the code
visited[cur_ver]=true;
means "take element 52 of the array myVec, and assign true to it". However, that element is not of type bool, but of type std::vector<int>. There is no operator that would allow to assign bool values to a vector object.
To specify the size of a vector, which is your intention, use the appropriate constructor or the resize() method. When you're sure that the size of your container is fixed and known at compilation time, you may use std::array<size_t, T>, which is a fixed-length array container, available in C++11. But this is not the case with your code - you insert elements later on.
Thus, to fix the error, fix the syntax for vector declarations, and then resize in your class' constructor:
vector<int> adj;
// other vectors follow ...
// in Circuit::Circuit:
Circuit:Circuit() {
adj.resize(51); // others follow ...
}
Be sure to replace the 51 with a properly named constant. "Magic" constants are evil!
Vectors are like dynamic arrays with an ability to resize. We've only two ways of the declaration of the vector in c++.
vector <int> myVector;
vector <int> myVector2(4,1000);
The second will initialize a vector of size 4 with initial value 1000. If you want to provide a size maybe you can use like this.
vector <int> myVector(12);
How would I use an enhanced for loop with a multidimensional array? (c++11, although feel free to answer for other versions)
We'll start with two dimensions...
int array[10][9];
//loop through first dimension (10)
for(int i : sizeof(array)) {
//do something
}
Compiler error: this range-based 'for' statement requires a suitable "begin" function and none was found
Could it have something to do with a multidimensional array being really still 1 dimension? In other words, int array[10][9] is equivalent to int array[90]
To use range based loops, you should pass a container in which the begin and end has beed defined. Try this:
for(auto &rows: array) // rows
{
for(auto &x: rows)
{
// ...
}
}
int array[10][9] is not equivalent to int array[19], it can be defined as int array[10*9].