내가 이렇게 어레이에서는 및 초기화하십시오 만들 수 있습니다.
int a[] = {10, 20, 30};
어떻게 생성합니까 초기화하십시오 partnernet 표준용량 벡터입니다 '와' 우아한?
The best way I know is:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
더 나은 방법이 있나요?
C++11 은 컴파일러와의 할 경우 됩니다.
std::vector<int> v = {1, 2, 3, 4};
이것은 GCC 에서 사용할 수 있는 [vmware. 버전 4.4] (http://gcc.gnu.org/projects/cxx0x.html). 이런 점에서 2010년 VC++ 죄송합니다. 뒤떨어져 있는 것으로 보인다.
또한 [부스트리아스니] (http://www.boost.org/doc/libs/1_42_0/libs/assign/doc/index.html) 를 사용하면 매직 매크로 비사양 library 는 다음과 같다.
#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
또는:
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;
하지만 이 보유하고 있는 점을 유념하십시오 오버헤드에 (기본적으로 'a', '아래' 구문을 list_of 데크 표준용량 후드요) 코드 you& 성능이 중요한 일을 더 잘할 수 있으므로, d # 39 로 오프하도록 야코비 말합니다.
현대의 C++ 사용할 수 있는 경우 [11.14,17.] 운행에서어떠한:
std::vector<int> vec = {10,20,30};
스이제로프 () '또는' 를 통해 기존 방식으로 루프을 가변길이배열 사용하여 불필요한 면에서 완전히 사악함이라 '는 정말 있는 눈과 정신 오버헤드에. 우웩.
C++0x 에 기대할 수 있는 것이 아니라 함께 같은 방식으로 재발했지 어레이에서는 현재 표준.
겨우 언어 지원 사용할 수 있습니다.
int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here
만약 다른 라이브러리를 추가할 수 있습니다 부스트 할당에서는 수도 있습니다.
vector<int> v = list_of(10)(20)(30);
크기를 하르코딩 피하기 위해 어레이에서는:
// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N]; // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))
C++11 에서:
#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };
향상시키십시오 사용하여 list_of:
#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);
향상시키십시오 사용하여 할당할지:
#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;
기존 STL:
#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
Stl 함께 기존 일반 매크로:
#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));
초기화 벡터 기존 STL 매크로:
#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);
그냥 내 토스 i& 돌아보; d # 39 만 0.02 달러 였다. 내가 이 너희가운데 경향이 있다.
template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
return std::vector<T>(data, data+N);
}
const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);
하지만 난 can& # 39, t C++0x 기다립니다. # 39 m, 내 코드 때문에 비주얼 스튜디오에서 컴파일하십시오 i& 갇혀 있어야 합니다. 부끄부끄.
시작으로:
int a[] = {10, 20, 30}; //i'm assuming a is just a placeholder
const int a[] = {10, 20, 30};
const std::vector<int> ints(a,a+sizeof(a)/sizeof(int)); //make it const if you can
#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);
C++11 있을 경우에는 컴파일러:
const std::vector<int> ints = {10,20,30};
초기화 벡터 -
vector<int> v = {10,20,30}
c++11 컴파일러와의 경우 수행할 수 있습니다.
그 후 배열입니다 루프지 대한 데이터를 사용할 수 있습니다
int array[] = {10,20,30}
for(unsigned int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
v.push_back(array[i]);
}
이 외에 다른 방법을 사용하여 여러 가지 위에 설명됨 일부 코드를. 제 생각에는, 이러한 방법을 쓸 빠르고 쉽게 기억할 수 있다.
바리아디스 매크로 는 컴파일러와의 경우, 즉 진정한 대부분의 현대 컴파일러에도) 한 후, 다음 한 줄 광고문 선반가공 벡터입니다 초기화하지 붙여넣습니다 매크로를 사용할 수 있습니다.
#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
이와 함께 다음과 같은 코드를 사용하여 충족되었으며 초기화되었습니다 벡터입니다 매크로를 정의할 수 있습니다.
INIT_VECTOR(int, my_vector, {1, 2, 3, 4});
이 새로운 벡터 의 정수 만들어 갈 것 "이라고 명명된 my_vector 요소와 함께 1, 2, 3, 4.
내가 내 스스로 va_arg 구축하십시오 이용하여 솔루션을 ''. 이 솔루션은 C++98 호환일.
#include <cstdarg>
#include <iostream>
#include <vector>
template <typename T>
std::vector<T> initVector (int len, ...)
{
std::vector<T> v;
va_list vl;
va_start(vl, len);
for (int i = 0; i < len; ++i)
v.push_back(va_arg(vl, T));
va_end(vl);
return v;
}
int main ()
{
std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
std::cout << *it << std::endl;
return 0;
}
[데모] (http://ideone.com/1lIACz)
std::vector<int> v;
v+=1,2,3,4,5;
그냥 이 청크에는 포함시키십시오 코드
template <class T> class vector_inserter{
public:
std::vector<T>& v;
vector_inserter(std::vector<T>& v):v(v){}
vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
return vector_inserter<T>(v),x;
}
더 최근의 복제본임을 질문 있는 이 질문에 에서 빅토르 세르. For me, it 는 컴팩트형 (# 39, & # 39 는 shoving& 것처럼 보이는데, 시각적으로 없다 # 39 의 값을), t · 회피 또는 제 3 자에게 모듈에서는 doesn& c++11 필요한 추가 (서면) 변수를 사용하여. 다음은 내가 어떻게 그것을 사용해 몇 번으로 변경. 난 과민반을을 전환하십시오 작동입니다 확대 및 / 또는 va_arg 벡터입니다 향후 안티드.
// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
public:
typedef mkvec<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
my_type& operator<< (const std::vector<T>& inVector) {
this->data_.reserve(this->data_.size() + inVector.size());
this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
std::vector<int32_t> vec1;
std::vector<int32_t> vec2;
vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5,8,19,79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1,2,3,5,8,19,79,10,11,12)
아래의 c++ 언어로 벡터입니다 초기화하지 방법을 사용할 수 있습니다.
[] 1. 'int = {1, 3, 5, 6} 도착. vector< int>; v (도착, 도착 + 스이제로프 (도착) / 스이제로프 (도착 [0]), '
', 3}, {1, 3, 5, 7 vector< int>, v ='
하나는 3 실점으로 c++11 에서 이다.
// Before C++11
// I used following methods:
// 1.
int A[] = {10, 20, 30}; // original array A
unsigned sizeOfA = sizeof(A)/sizeof(A[0]); // calculate the number of elements
// declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA); // make room for all
// array A integers
// and initialize them to 0
for(unsigned i=0; i<sizeOfA; i++)
vArrayA[i] = A[i]; // initialize vector vArrayA
//2.
int B[] = {40, 50, 60, 70}; // original array B
std::vector<int> vArrayB; // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
vArrayB.push_back(B[i]); // initialize vArrayB
//3.
int C[] = {1, 2, 3, 4}; // original array C
std::vector<int> vArrayC; // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0])); // enlarging the number of
// contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
vArrayC.at(i) = C[i]; // initialize vArrayC
// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.
뭔가 스케쳐내 대한 의존도를 만들지 않고, 다음은 순서에 따라 동일한 일반적인 할당할지 향상시키십시오 향상시키십시오 적어도 생기기 유사물:
template<class T>
class make_vector {
std::vector<T> data;
public:
make_vector(T const &val) {
data.push_back(val);
}
make_vector<T> &operator,(T const &t) {
data.push_back(t);
return *this;
}
operator std::vector<T>() { return data; }
};
template<class T>
make_vector<T> makeVect(T const &t) {
return make_vector<T>(t);
}
I wish 구문은 전송되었기 클리너, 동시에 사용하여 it& # 39 의 아직 매우 끔찍해.
std::vector<int> x = (makeVect(1), 2, 3, 4);
하지만 내가 좋은 일을 많이 있는데 여기에 대답을 내 스스로 이 읽기 전에 도착한 이후 독립적으로 I& 생각했어요; d # 39 토스 내거냐 여기에 겁니다.
구조체입니다 또는 클래스를 컨테이너입니다 객체에는 모음집을 만들 수 있다. 연산자에서 정의하십시오 오버로드할 기능을 < <;).
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
예를 들어, 어떤 함수의 매개 변수로 구조체입니다 경험하십시오 만들 수 있습니다.
someFunc( MyObjectList &objects );
그 후, 다음과 같은 함수를 호출할 수 있습니다
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
그러면 반드시 크기를 동적으로 객체를 컬렉션을 구축할 수 있는 기능을 하나로 청소하십시오 선!