Reputation:
I am new to C++, so this is probably just a simple mistake, but when I try to create a vector of integer arrays, for example vector <array<int, 3>> triangles = ({0, 1, 2}, {3, 4, 12});
, I get this error:
error: expected ';' before '}' token
vector <array<int, 3>> triangles = ({0, 1, 2}, {3, 4, 12});
^
I am using the CMake version included with CLion 2020.1.1 for compilation. The full script is below:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main() {
vector<array<int, 3>> triangles = ({1,2,3},{2,3,4});
cout << triangles;
return 0;
};
Thank you, any help is greatly appreciated :)
Upvotes: 0
Views: 207
Reputation: 1081
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
int main() {
vector<array<int, 3>> triangles = {{1,2,3},{2,3,4}};
for_each (triangles.begin(), triangles.end(), [](array<int,3> arr) {for (int item2 :arr) {cout << "[" << item2 << "]"<< endl; ;}});
return 0;
};
Upvotes: 0
Reputation: 4253
Instead of brackets ({1,2,3},{2,3,4}) you should be using curly braces for initializer list: {{1,2,3},{2,3,4}};
Also there is no default operator<< for vector - you have to define your own.
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main() {
vector<array<int, 3>> triangles = {{1,2,3},{2,3,4}};
//cout << triangles; // there is no default operator<< for vector - you have to define one on yourself
return 0;
}
for example:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
using MyContainer = vector<array<int,3>>; // using type-alias for making life easier
ostream& operator<<(ostream& os, const MyContainer& v)
{
for (const auto& arr : v)
{
for (const auto& el : arr)
os << el << " ";
os << "\n";
}
return os;
}
int main() {
MyContainer triangles {{1,2,3},{2,3,4}};
//cout << triangles; // there is no default operator<< for vector - you have to define one on yourself
cout << triangles;
return 0;
}
Output:
1 2 3
2 3 4
Upvotes: 1
Reputation: 9366
Your syntax is incorrect, hence the error.
Try the following:
int main() {
vector<array<int, 3>> triangles {{1,2,3},{2,3,4}};
//cout << triangles;
for (const auto& triangle : triangles)
for (const auto i : triangle)
cout << i << '\n';
return 0;
};
Moreover, you can not directly output a vector
. You have to iterate over its elements and print them out one by one.
vector<array<int, 3>> triangles {{1,2,3},{2,3,4}};
syntax is known as "direct-list initialization", while vector<array<int, 3>> triangles = {{1,2,3},{2,3,4}};
is "copy-list initialization". Read more about them here: Differences between direct-list-initialization and copy-list-initialization
Upvotes: 0