Error using complex vector - c++

I need to access a specific element of a vector of complex data in C++.
Here is what I have:
vector< complex<float> > x; // Create vector of complex numbers
x.push_back(complex<float>(1, 2)); // Place 1 + j2 in vector
x.push_back(complex<float>(2, 1)); // Place 2 + j1 in vector
// Attempt at accessing the zero-th elements real part
float temp1 = x.at(0).real;
float temp2 = x[0].real;
This gives the following error in Visual Studio 2015:
Severity Code Description Project File Line Suppression State
Error C3867 'std::_Complex_base::real': non - standard syntax; use '&' to create a pointer to member opencv_dft c : \users\josh\VS_project\main.cpp 101

You forgot the parentheses in the calls to real(). You need:
float temp1 = x.at(0).real();
float temp2 = x[0].real();
real() is a member function, not a data member.

No need for casting in statement x.push_back(complex(float){1, 2})-though doesn't hurt to cast. Also don't forget using namespace std for statements using vector and complex.
Also don't forget ()s in x.at(0).real so it is x.at(0).real();.
Here is how I wrote a program using vectors and complex numbers.
#include <iostream>
#include <complex>
#include <vector>
using namespace std;
void main() {
complex<float> a = { 1,2 };
a = { 1,4 };
vector<complex<float>> av;
av.push_back({ 1,2 });
cout << av.at(0).real();
}

Related

Classes with Armadillo data

Initially, I was importing some data from R directly into a C++ function like so:
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::depends(RcppArmadillo)]]
List gibbs(List dat) {
int N = dat["N"];
arma::vec y = dat["y"];
...
}
Eventually, I needed more than just N and y (the input_data list has many separate vectors and matrices I need to import). So, I thought it would be a good idea to create a class Data to store all the input variables and automatically do some pre-processing in the constructor. Something like
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::depends(RcppArmadillo)]]
class Data {
public:
int N;
arma::vec y;
// other data
Data(List input_data) {
N = input_data["N"];
y = input_data["y"];
// pre-processing steps
}
};
However, this doesn't work. It gives the following error:
object_LocLev.cpp:12:7: error: use of overloaded operator '=' is ambiguous (with operand types 'arma::vec' (aka 'Col<double>') and 'Rcpp::Vector<19>::NameProxy' (aka 'generic_name_proxy<19>'))
y = input_data["y"];
~ ^ ~~~~~~~~~~~~~~~
My question is why does this error appear? Is there a better way of assigning y?

Copy assign json-Container to vector

I am trying to convert a json-Container from the JSON-library JSON for Modern C++ to a vector, but it does not work with the =-operator (I get a compiler error "more than one operator "=" matches these operands").
A minimum working example:
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
int main()
{
vector<double> v = { 0 , 10 , 20 , 100 };
json j(v);
vector<double> copy = j;
vector<double> copyWithAssign;
//copyWithAssign = j; // more than one operator "=" matches these operands
return 0;
}
You can find the json.hpp here.
Using the constructor with vector<double> copy = j; works and I could write copyWithAssign = copy; but that seems dumb. There must be a direct way to assign j to a vector which has been declared and constructed before.
I thought casting might help since the compiler can't decide which type to use. I tried (vector<double>)j, but that didn't help.
One should use
copyWithAssign = j.get<vector<double>>();
Credits go to theodelrieu who posted this answer here.

Declaration of Vectors

Vectors size dynamically, so why is this giving a seg fault:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
vector<int> vectorOfInts;
vectorOfInts[0] = 3;
}
What I'm trying to actually do is declare a vector in a class.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Directory{
public:
string name;
int maxIndex;
vector<Directory> subDirectories;
void addSubdirectory(string x){
Directory newSubdirectory(x);
subDirectories[maxIndex++] = newSubdirectory;
}
Directory(string x){
name = x;
maxIndex = 0;
}
};
int main(){
Directory root("root");
root.addSubdirectory("games");
}
But this also gives a seg fault.
Vectors don't resize entirely automatically. You use push_back or resize to change the size of a vector at run-time, but the vector will not automatically resize itself based on the index you use--if you index beyond its current size, you get undefined behavior.
In your demo code, you could do something like this:
vector<int> vectorOfInts(1);
vectorOfInts[0] = 3;
Alternatively, since you're just adding 3 to the end of the existing data (or nonexistent data, in this case) you could just use push_back (or emplace_back):
vector<int> vectorOfInts;
vectorOfInts.push_back(3);
It looks like the same basic approach will work with your real code as well. It also simplifies things a bit, since you don't need to explicitly track the maxIndex as you've done.
A default-constructed vector has no elements (i.e. its size() returns zero).
The operator[] does not check if it is supplied a valid index, and gives undefined behaviour if supplied an invalid index. It does not resize the vector. A vector with size zero has no valid indices.
That combination explains your problem.
The seg fault, come from the fact that you try to acces an element that does not exist. When you use operator [ ], be sure that you already alocate memory for this element using resize, push_back, emplace_back...
To make your code work, just replace this
void
addSubdirectory(string x)
{
Directory newSubdirectory(x);
subDirectories[maxIndex++] = newSubdirectory;
}
by
void
addSubdirectory(string x)
{
subDirectories.emplace_back(x); // c++11
// else subDirectories.push_back(Directory(x));
}
and you don't need the maxIndex, you can have it using the size method: subDirectories.size() - 1.

Trouble iterating through a list

I'm working on this project that basically reads information from a file, use that information on an object and then creates a list that contains the objects.
I have a class named Acao which basically contains a few pieces of information, some strings and some floats. Pretty simple;
What I'm trying to do in order to check if my list is being correctly built is to output a float named cMed using the getcMed() member from Acao class.
Ok, first of all:
I'm getting three errors while trying to iterate through my list, being with operators =, != and ++.
All of them being - repectively:
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::_List_iterator<std::_List_val<std::_List_simple_types<Acao>>>' (or there is no acceptable conversion)
As much as I don't think that really matters in this case, these are my included libs:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <stdlib.h>
#include <sstream>
Now then, my second problem with this piece of code is with the line:
cout << (*it)->getcMed();
Both my list and the iterator it are of Acao type, but my compiler (I'm using VS 2013 for my IDE and compiler) gives me the following error:
error C2039: 'getcMed' : is not a member of 'std::list>'
Here's the chunk of code in question (also note: I'm using namespace std for this):
list<Acao> novaListaAcoes(){
fstream file;
streampos begin;
list<Acao> listaAcoes, it;
Acao A;
string linha, papel, companhia, tipo;
float min, med, max;
file.open("G:\\VS\\ConsoleApplication4\\BDINaux.txt");
file.clear();
file.seekg(0, ios::beg);
listaAcoes.clear();
while (!file.eof()){
getline(file, linha);
if (file.eof()){ break; }
vector<char> vector(linha.begin(), linha.end());
min = calcMin(vector);
max = calcMax(vector);
med = calcMed(vector);
papel = lePapel(vector);
companhia = leComapanhia(vector);
tipo = leTipo(vector);
vector.clear();
A.setCompanhia(companhia);
A.setCotacao(med, min, max);
A.setNomePapel(papel);
cout << papel<< endl;
listaAcoes.push_back(A);
}
cout << "fim loop\n";
for (it = listaAcoes.begin(); it != listaAcoes.end(); ++it){
cout << (*it)->getcMed();
}
return listaAcoes;
}
Your declaration:
list<Acao> listaAcoes, it;
Doesn't match the type needed for the assignment statement in the for loop initializer:
for (it = listaAcoes.begin(); // <<<
Make a separate declaration for it:
list<Acao>::iterator it;
An iterator is a concept for c++ container classes, but not equivalent to a class instance of those itself!
The idiom I personally prefer, is to declare variables closest to their use, such for a for loop:
for (std::list<Acao>::iterator it = listaAcoes.begin();
it != listaAcoes.end();
++it)
{
// Access it's underlying Acao instance using -> or * dereference operators
}

Error trying to access a struct type using a pointer to a vector of structs

#include <iostream>
#include <vector>
using namespace std;
struct a_struct { int an_int; };
int main ()
{
vector <vector <a_struct> > the_vec;
vector <a_struct> * p_vs;
p_vs = & the_vec[0];
*(p_vs)[0].an_int=0; //error: 'class __gnu_debug_def::vector<a_struct,
//std::allocator<a_struct> >' has no member named 'an_int'
}
I can't figure out why I'm getting the above compile error.
In C++, [] and . have higher precedence than *.
Your last line
*(p_vs)[0].an_int=0;
when fully parenthesized, is
*((p_vs[0]).an_int)=0;
Since p_vs was declared as
vector <a_struct> * p_vs;
it is as if p_vs is an array of vector <a_struct> elements, so p_vs[0] is a vector<a_struct>.
And vector<a_struct> objects indeed do not have a member an_int.
Add some parens and you will get what you want.