I have an array of vector of pairs
vector <pair<int,int> > a[4]
.I have added elements to it using push_back.But I dont know how to print the elements.if i use an iteretor and print it like a[i].first or a[i].second it throws me error .Any other ways of doing it.Thanks in advance.
vector <pair<int,int> > a[4];
for(int i = 0;i < e;++i)
{
int x,y;
cin >> x >> y >> w;
a[x].push_back({w, y});
a[y].push_back({w, x});
}
This is how I push elements.But how to print them.
for(i=a[i].begin();i!=a[i].end();i++)
{
cout<<a[i].second<<" ";
}
I am getting the following error.I dnt know how to print them.
error: no match for 'operator[]' (operand types are 'std::vector<std::pair<int, int> >*' and 'std::vector<std::pair<int, int> >::iterator {aka __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int> > >}')
for(i=g[i].begin();i!=g[i].end();i++)
You did not provide any code so that we could be able to know what's going wrong at your machine.
But here is a working example on how to access a vector of pairs:
#include <utility>
#include <iostream>
#include <vector>
#include <string>
typedef std::pair<int, std::string> pairIntString;
int main()
{
std::vector<pairIntString> pairVec;
pairVec.push_back(std::make_pair(1, "One"));
pairVec.push_back(std::make_pair(2, "Two"));
pairVec.push_back(std::make_pair(3, "Three"));
for (std::vector<pairIntString>::const_iterator iter = pairVec.begin();
iter != pairVec.end();
++iter)
{
std::cout << "First: " << iter->first
<< ", Second: " << iter->second <<std::endl;
}
return 0;
}
Output, see here:
First: 1, Second: One
First: 2, Second: Two
First: 3, Second: Three
Edit #1:
Now you provide code, but you are actually using an array of vectors of pairs: vector <pair<int,int> > a[4];. Further you put an iterator from the begin() method into the [] operator. It seems that you mixed a lot of things e.g. here i=a[i].begin() (one i is iterator and another is an index) and don't understand what they really are for. Please look at my example and read about arrays and vectors and how to access them properly. Also read about the difference of indexed and iterator based access.
Edit #2:
This loop:
for(i=a[i].begin();i!=a[i].end();i++)
{
cout<<a[i].second<<" ";
}
should probably be:
/* loop through the fixed size array */
for(size_t idx = 0; idx < 4; ++i)
{
cout << "Array element idx: " << idx << endl;
/* get the iterator of the specific array element */
for (vector <pair<int,int> >::const_iterator iter = a[idx].begin();
iter != a[idx].end();
++iter)
{
cout << "First: " << iter->first
<< ", Second: " << iter->second << endl;
}
}
as you're having an array of vector of pairs you have two loop over the array and the vector. Because the array has a fixed size of 4 I used it as maximum.
vector <pair<int,int>> vec[5];
vector <pair<int,int>> :: iterator it;
for(int i=0;i<5;i++){
for(it=vec[i].begin(); it!=vec[i].end();it++) cout << it->first << " " << it->second << " -> ";
cout << "\n";
}
vector<pair<int,int>> v;
int n , in1 , in2;
cin >> n;
for(int i = 0 ; i < n ; i++)
{
cin >> in1 >> in2;
v.push_back(make_pair(in1,in2));
}
for(int i = 0 ; i < n ; i++)
cout << v[i].first << " " << v[i].second << endl;
return 0;
I used this concept in a question and you can check out the code which do the same what you wanted
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define loop(i, k, n) for(int i = k; k < n ? i < n : i >= n; k < n ? i+=1 : i-=1)
#define pll pair<ll, ll>
#define pb push_back
#define po pop_back
#define mp make_pair
#define F first
#define S second
#define endl "\n"
int main()
{
ll n, k;
cin >> n >> k;
ll arr[n];
ll ansArr[n] = {0};
vector <pair<ll, ll>> v[n];
loop(i, 0, n) cin >> arr[i];
loop(i, 0, n) {
if(arr[i] < 0) {
for(int j = i+1; j <= i+k && j < n; j++) {
if(arr[j] > 0) v[j].pb(mp(arr[i], i)); // Taking input in pairs
}
for(int j = i-1; j >= i-k && j >= 0; j--) {
if(arr[j] > 0) v[j].pb(mp(arr[i], i)); // Taking input in pairs
}
}
}
// Printing the result
loop(i, 0, n) {
for(auto it : v[i]) cout << it.F << " ";
cout << endl;
for(auto it : v[i]) cout << it.S << " ";
cout << endl;
}
return 0;
}
Related
i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}
I am trying to make program which finds max and min element of vector, and and outputs elements in the interval min max, but skips those that were specified in the vector.
For example:
in: 2 6 7
min is 2, max is 7
out: 3 4 5
But I have error message: vector subscript out of range
The code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int size;
cout << "Enter size:" << endl;
cin >> size;
vector <int> vect;
vect.resize(size);
for (int j = 0; j < vect.size(); j++)
{
cout << "Enter " << j << " element: ";
cin >> vect[j];
cout << endl;
}
cout << "Your first vector: " << endl;
for (int j = 0; j < vect.size(); j++)
{
cout << vect[j] << " ";
}
cout << endl;
int min = *min_element(vect.begin(), vect.end());
int max = *max_element(vect.begin(), vect.end());
for(int j = min; j<max;j++)
{
if (vect[j] != j)
{
cout << j;
}
}
system("pause");
return 0;
}
You can use the std::find along with the computed min and max:
for (int i = min + 1; i < max; ++i)
if (std::find(vect.begin(), vect.end(), i) == vect.end())
std::cout << i;
This is not the most efficient solution (e.g. If you sort the vector, then you don't need to repeatedly call find).
Also, be careful when dereferencing the result of max/min_element if vect is empty. If you do that, you invoke undefined behaviour.
Note that there is a minmax_element that will give you both iterators at the same time, which is much nicer.
min and max will return min and max values of the vector. Instead checking with min and max, Check in range[0,vect.size()]
for(int j = 0; j<vect.size();j++)
{
if (vect[j] !=min && vect[j]!= max)
{
cout << j;
}
}
void IntegerReversed(int* a, int n)
{
if (n < 1) {
return;
}
else {
cout << a[n - 1] << endl;
Integer(a, n - 1);
}
}
int main()
{
int* a;
int n;
cout << "Input n: ";
cin >> n;
a = new int[n];
for (int i = 0;i < n;i++) {
cin >> *(a + i);
}
cout << "Integer values reversed in array: " << endl;
IntegerReversed(a, n);
}
Hi this my code to output the array of integer values to screen in reversed order using recursion.
but it only prints the first correct element
Input : a[4]={1,2,3,4}
But output :
4 , 1 , 2 , 3
I want to print :
4 , 3 , 2 , 1
Can you help my fix this code
i tested your program..
void IntegerReversed(int* a, int n)
{
if (n < 1) {
return;
}
else {
cout << a[n - 1] << endl;
IntegerReversed(a, n - 1);
}
}
and this was just a spellling mistake..
in recursive call..
While I get that this is probably an exercise in recursion itself, it's definitely not needed for this problem, since vectors (and most Standard Library containers) have built-in abilities to iterate in reverse.
#include <iostream>
#include <vector>
int main() {
int numElements;
std::cout << "Number of Elements: ";
std::cin >> numElements;
std::vector<int> arr(numElements);
for (int i = 0; i < numElements; ++i) {
std::cin >> arr[i];
}
for (auto rit = arr.rbegin(); rit != arr.rend(); ++rit) {
std::cout << *rit << ' ';
}
std::cout << '\n';
}
I´m trying to assign values to a multidimensional vector, but I always get an "R6010 - abort()" error from visual studio.
What I want is an two dimensional vector, where the second dimension is exactly as large as needed. (Important because I don't now how many input values and I want to use later myvector.at(i).size();
So to formulate it short: Why is the following example not working?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < vector < int > > Vektor;
Vektor.resize(10);
int tmp;
while (true) {
cout << "Please enter a value: " << endl;
cin >> tmp;
int size;
if (tmp > 0 & tmp < 11) {
Vektor.at(tmp - 1).push_back(tmp);
}
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
for (int j = 0; j < size; j++) {
cout << "Value at " << i << " , " << j << " : " << Vektor.at(i).at(j) << endl;
}
}
}
return 0;
}
You are using wrong indices in the lines:
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
Change the lines to:
| ||
v vv
for (int i = 0; i < 10; i++) {
size = Vektor.at(i).size();
As already answered by #RSahu, you use wrong indices in a loop. In stead of correcting the values, I'll suggest that you avoid hard coded values.
That can be done in several ways. By using vector.size() your code is easy to fix. Just use these two lines instead of your current two lines:
if (tmp > 0 & tmp <= Vektor.size()) {
for (int i = 0; i < Vektor.size() ; i++) {
An alternative way of printing could be
size_t i = 0;
for (const auto& v : Vektor)
{
size_t j = 0;
for (const auto e : v)
{
cout << "Value at " << i << " , " << j << " : " << e << endl;
++j;
}
++i;
}
So I have 2 arrays. Let's say the first one it's called a and the second one b. The first one uses "i" for it's elements and the second one uses "j".
For example we have a[ 1 2 3 4] and b[3 4 5] it should show c[1 2]. In the array c I want to show the elements that are in a and aren't in b.
This is what I've tried, but without succes:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
If the items are sorted, use std::set_difference:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 3, 4, 5 };
std::vector<int> cv;
std::set_difference(std::begin(a), std::end(a),
std::begin(b), std::end(b),
std::back_inserter(cv));
for (auto& s : cv)
std::cout << s << "\n";
}
Output:
1
2
The advantage of using the STL algorithms is that the purpose of the code is known immediately just by looking at the name of the function, and that they work every time (if you give them the correct parameters). Note the lack of comments -- any competent C++ programmer understands right away what's being done.
On the other hand, if you didn't mention what your original code was trying to do (including removing the comments), it would take much more effort to figure out what it's supposed to be doing, and as you've seen, it contains bugs.
Your logic is wrong.
Explanation
So the thing that we will do
For each element in a we will have to check if it is there in array b or not.
If we see any element of a[i] in b[1..m] then we can't add it to c.
So in code we just mark it by f=1
When I get out of that second for loop I want to check if that a[i] is eqaul to any of the element in b[1..m] in which case f will be 1. But if it is 0 then add it to array c[].
Correct one
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
Where OP went wrong?
Being not equal to one element of b[] doesn't guarantee that the element is not appearing b[0..m-1] . This is where op went wrong.
In the for loop
for(j=0;j<m;j++) you are checking if particular a[i] is equal to b[j] or not. If that is the case then it is added to c[] . It is wrong. Also i is not incremented in the loop unless j==m and as in the for loop the condition is j<m so i is never incremented. And k is incremented every time so not every element in c is valid they may contain garbage value even after processing.
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j]) // this doesn't mean that it is not appearing in `b`
c[k] = a[i];
k++; // k is incremented in every iteration which is wrong. It should be only when we are sure that `a[i]` is not in `b[0..m-1] `
while (j == m && i < n)
i++; // OP is not using it anywhere...this is redundant.
}
what op did?
Compared first element of a[0] with every element of b[0..m-1] and array c[] contains m elements irrespective of what a[] and b[] is, out of which
c[i]={ a[0] if b[j]==a[0]
{ garbage value if b[j] not equal to a[0]
Dry Run of OP's code
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
Input
Case: 1 2 3 4 :a[]
2 3 4 1 :b[]
Step 1: i=0 a[0]!=b[0] is true so c[0]=a[0]. the `while loop` not entered.
j++
Step-2: i is still 0. a[0]!=b[1] so it is added c[1]=a[0]. While loop not entered.
j++
Step-3: i is still 0. a[0]!=b[2]. So c[2]=a[0]. While loop skipped.
j++
Step-4: i is still 0. a[0]==b[3] is true so no assignment done. But k is incremented. so c[3]=garbage. j=3 so while loop skipped
j++
Out of for loop.
Output: [here x is garbage value]
a[]: 1 2 3 4
b[]: 2 3 4 1
c[]: 1 2 3 x
Example test case
1 2 3 4 :=a
2 3 4 1 :=b
Corrected Code
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
{
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
Your code seems to check if the elements in a are equal to all elements of b. If you just want to check the elements in a if they are equal to at least one element of b, you can do
for (int i=0; i<n; i++) {
bool found = false;
for (int j=0; j<m; j++) {
if (a[i] == b[j]) {
found = true;
break;
}
}
if (!found) {
std::cout << "a["<<i<<"] is not in b"<<std::endl;
}
}
Or add the element to c, but I would recommend to use std::vector<int> c for that.
In the array c I want to show the elements that are in a and aren't in b
It seems like you are looking for std::set_difference
int a[4] = {1, 2, 3, 4}, b[3] = {3, 4, 5};
int c[2] = {}; // declare c with enough space to hold all the elements in result
std::set_difference(a, a + 4, b, b + 3, c); // now c contains the element that are in a but not in b
You can do this very easily using 'set'.
#include<iostream>
#include<set>
int main(){
std::set<int> a = {1,2,3,4} , b = {3,4,5};
for(int const inB : b)
a.erase(inB);
for(int const inA : a)
std::cout << inA << " ";
std::cout << std::endl;
return 0;
}