There are 4 ways to access the elements of vector in C++. (from chatgpt)

 

  1. Using Subscript Operator ([]): You can access vector elements using the subscript operator. Remember that vector indices start from 0.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    for (size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }

    return 0;
}
  1. Using Iterator: You can use iterators to traverse through the elements of a vector. This is particularly useful when you want to work with elements in a generic way.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}
  1. Using Range-Based For Loop (C++11 and later): C++11 introduced range-based for loops, providing a concise way to iterate through elements.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    for (const auto& num : numbers) {
        std::cout << num << " ";
    }

    return 0;
}
  1. Using at() Member Function: The at() member function allows you to access elements with bounds checking. It throws an out_of_range exception if the index is out of bounds.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    for (size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers.at(i) << " ";
    }

    return 0;
}

'C++' 카테고리의 다른 글

inline function defined in source file? or header file?  (0) 2024.01.20
try-throw-catch  (1) 2024.01.20
while(cin >> x)  (0) 2024.01.20
switch-case  (0) 2022.06.11
down up casting  (0) 2022.06.08

나의 센서 챗지피티 형님께 여쭤봤다.

형의 대답은 다음과 같다.

 

  1. Visibility and Inlining Across Translation Units:
    • When an inline function is defined in a header file, its definition is available to multiple translation units (source files). This allows the compiler to potentially inline the function in each translation unit where it is used.
    • Placing the definition in a source file might limit the compiler's ability to inline the function across multiple source files.
  2. One Definition Rule (ODR):
    • If an inline function is defined in multiple translation units, the definitions must be identical. Placing the definition in a header file helps ensure consistency across different source files.
  3. Ease of Use:
    • Including the header file with the inline function definition allows users of your code to benefit from inlining without having to manually duplicate the function definition in each source file.

해석하자면,

 

1. 번역단위의 가시성과 인라이닝

  * 헤더파일에 정의해 놓으면, 여러 소스파일에서 번역하여 사용 가능해진다. 이건 컴파일러가 각 번역마다 함수를 인라인할 수 있게 해준다.

   * 함수 정의를 소스파일에 해놓으면 컴파일러가 여러 소스파일에 인라인을 할 수 있는 것이 제한적이된다.

-> 거의 비슷한 말인 듯 하다. 헤더파일에 해 놓으면 해당 헤더파일을 include 하는 소스파일들은 정의된 인라인을 사용할 수 있게 되지만, 소스파일에만 정의되어 있을 경우, 해당 소스파일에만 적용이 가능하다.

 

2. 1회 정의 룰

  * 중복되어 정의되어서는 안된다.

 

3. 쉬운 사용

  * 여러 소스파일에서 정의하지 않아도 된다. 곧 헤더파일에 정의해놓으면 귀찮게시리 사용하는 소스파일마다 정의하지 않아도 된다는 뜻.

 

역시 센세.

'C++' 카테고리의 다른 글

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
try-throw-catch  (1) 2024.01.20
while(cin >> x)  (0) 2024.01.20
switch-case  (0) 2022.06.11
down up casting  (0) 2022.06.08

C에서는 보통 예외처리라 하면 조건문? 아니면 assert? 정도 일듯한데,

 

객체지향의 C++은 try~catch 구문이 있다.

 

아래 코드는 chatgpt가 생성해준 코드인데, 심플해서 이해하기 좀 쉽네.

#include<iostream>
#include<stdexcept>

using namespace std;

double divide(int numerator, int denominator)
{
    if(denominator == 0)
    {
        throw invalid_argument("Division by zero is not allowed");
    }

    return static_cast<double>(numerator / denominator);
}

int main()
{
    try{
        int numerator, denominator;

        // Get input from the user
        cout << "Enter numerator: ";
        cin >> numerator;

        cout << "Enter denominator: ";
        cin >> denominator;

        double ret = divide(numerator, denominator);

        cout << "result: " << ret << endl;
    } catch(const exception& e){
        cerr << "Exception caught: " << e.what() << endl;
    }
    return 0;
}

'C++' 카테고리의 다른 글

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
inline function defined in source file? or header file?  (0) 2024.01.20
while(cin >> x)  (0) 2024.01.20
switch-case  (0) 2022.06.11
down up casting  (0) 2022.06.08

제목의 코드 너무 간단하다.

근데 이해가 안되서 미칠뻔 함. 내 iq의 재발견.

코드를 쓰기도 참 거시기하지만, 대충 이런 느낌이다.

#include<iostream>

int main()
{
	int x;
	while(cin >> x)
	{
		cout << "read: " << x << endl;
	}
	return 0;
}
 
 

while 문에서 조건이 입력을 받은 값을 x에 넣는건데, 어떤 경우가 false인지..

 

일단 해보니 값이 저장되는 변수 x의 데이터타입에 따라서 true, false가 나뉘어지는 것 같다.

 

만약, int 형일경우, 정수 범위의 값만 받고, 나머진 false처리된다.

char형일 경우, 문자로 표현될 수 있는 값은 모두 true고 나머진 false 인 것 같다.

 

뭔가 이런 느낌인 듯 하다.

 

완전히 정확하진 않지만, 간단히 테스트한 결과다. 쉽지 않네?

'C++' 카테고리의 다른 글

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
inline function defined in source file? or header file?  (0) 2024.01.20
try-throw-catch  (1) 2024.01.20
switch-case  (0) 2022.06.11
down up casting  (0) 2022.06.08

C로 코딩할 때 swith 문을 많이 사용한다.그리고 지금까지 별 문제없이, 아니 아무 생각없이 썼다.

근데.. 문제가 생겼다. 일반적으로 swtich 문에서 case 구절에서 중괄호를 쓰지 않는다. 그리고 아래 코드 역시 중괄호 없이 그냥 코딩 했다.

switch(shapeChoice){
        case 1 :
            Line * l = new Line();
            v.push_back(l);
            break;
        case 2 :
            Circle * c = new Circle;
            v.push_back(c);
            break;
        case 3 :
            Rect * r = new Rect;
            v.push_back(r);
            break;
        default :
            break;
    }

굉장히 평범해보인다. 무척 자연스럽다. 하지만 컴파일이 안된다. 아무리 해도 안되고, 왜 안되는지 도저히 알 수가 없었다.

 

main.cpp:40:14: error: jump to case label
   40 |         case 3 :
      |              ^
main.cpp:33:20: note:   crosses initialization of 'Line* pLine'
   33 |             Line * pLine = new Line;
      |                    ^~~~~
main.cpp:44:9: error: jump to case label
   44 |         default :
      |         ^~~~~~~
main.cpp:33:20: note:   crosses initialization of 'Line* pLine'
   33 |             Line * pLine = new Line;
      |                    ^~~~~

 

인터넷에 찾아보니.. case 문 안에서 변수나 클래스를 선언할 경우, 중괄호를 사용해야한다. 예를 들면 이런거다.

switch(tmp)
{
	case 1:
		int a;
		a = 1;
		break;
	case 2:
		a = 4;
		break;
}

코드에서 보면 case 1: 에서 int가 선언되었고, 중괄호를 없어서 하나의 스코프로 컴파일러는 인식할 수 있다. 하지만 case 구역은 분리되어 있어 엄연히 다른 구역이다. 때문에 case 2: 로 바로 가면 오류가 발생할 수 있다. 아무래도 컴파일러는 이를 미연에 방지하고자 case 문 안에서는 반드시 중괄호를 치도록 하는 것 같다.

 

중괄호를 사용 후 잘 된다.

'C++' 카테고리의 다른 글

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
inline function defined in source file? or header file?  (0) 2024.01.20
try-throw-catch  (1) 2024.01.20
while(cin >> x)  (0) 2024.01.20
down up casting  (0) 2022.06.08

추상 클래스의 순수 가상함수가 연산자함수다. 이를 구체화 하는 파생클래스에서는 업캐스팅과 다운캐스팅의 과정이 필요하다.

업캐스팅 : 기본클래스 포인터가 파생클래스를 가리킨다 -> 포인터는 기본클래스의 멤버만 접근 가능

다운캐스팅 : 파생클래스 포인터가 기본클래스를 가리킨다 -> 포인터는 기본 및 파생 클래스의 멤버에 접근 가능

 

업, 다운캐스팅이 필요한 상황은 다음과 같다.

같은 클래스를 상속받는 두 파생클래스가 같은 기능의 함수에 매개변수로 들어가야 한다면, 굳이 함수를 따로 두개로 만들지 않고 매개변수로 업캐스팅 후 함수 안에서 다운캐스팅한다.

class Comparable{
public:
    virtual bool operator > (Comparable& op2) = 0;
    virtual bool operator < (Comparable& op2) = 0;
    virtual bool operator == (Comparable& op2) = 0;
};

class Circle : public Comparable{
    int radius;
public:
    Circle(int radius=1) { this->radius = radius; }
    int getRadius(){ return radius; }
    bool operator > (Comparable& op2);
    bool operator < (Comparable& op2);
    bool operator == (Comparable& op2);
};

bool Circle::operator > (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius > pc->getRadius()) return true;
    else return false;
}

위의 코드에서 순수 가상 연산자 함수의 매개변수의 데이터타입은 기본클래스다. 파생클래스 Circle에서 해당 함수를 구체화 하기 위해서 다시 다운캐스팅하고, 파생클래스의 멤버변수로 접근해서 기능을 작성한다. 이처럼 공통된 함수를 같이 쓰기 위해서 업다운 캐스팅 작업이 필요하다.

 

아래는 전체 코드이다.

#include <iostream>
using namespace std;


class Comparable{
public:
    virtual bool operator > (Comparable& op2) = 0;
    virtual bool operator < (Comparable& op2) = 0;
    virtual bool operator == (Comparable& op2) = 0;
};

class Circle : public Comparable{
    int radius;
public:
    Circle(int radius=1) { this->radius = radius; }
    int getRadius(){ return radius; }
    bool operator > (Comparable& op2);
    bool operator < (Comparable& op2);
    bool operator == (Comparable& op2);
};

bool Circle::operator > (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius > pc->getRadius()) return true;
    else return false;
}

bool Circle::operator < (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius < pc->getRadius()) return true;
    else return false;
}

bool Circle::operator == (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius == pc->getRadius()) return true;
    else return false;
}

template <class T>
T bigger(T a, T b){
    if(a > b) return a;
    else return b;
}

int main(){
    int a = 20,  b = 50, c;
    c = bigger(a, b);
    cout << "Which one is bigger 20 and 50 ? " << c << endl;
    /* These instances will be up casting to be parameter */
    Circle waffle(10), pizza(20), y;
    y = bigger(waffle, pizza); // Shoule be intger value
    cout << "The radius which has bigger radius waffle and pizza is " << y.getRadius() << endl;
}

/*
Which one is bigger 20 and 50 ? 50
The radius which has bigger radius waffle and pizza is 20
*/

'C++' 카테고리의 다른 글

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
inline function defined in source file? or header file?  (0) 2024.01.20
try-throw-catch  (1) 2024.01.20
while(cin >> x)  (0) 2024.01.20
switch-case  (0) 2022.06.11

+ Recent posts